Home > Web Front-end > JS Tutorial > Why Does `console.log` Appear Before Async Function Results in Top-Level `async` Code?

Why Does `console.log` Appear Before Async Function Results in Top-Level `async` Code?

Susan Sarandon
Release: 2024-12-17 18:45:18
Original
646 people have browsed it

Why Does `console.log` Appear Before Async Function Results in Top-Level `async` Code?

Why Does Asynchronous Execution Occur After Log Message in Top-Level Async Function?

In async/await, it's assumed that async functions will return promises. However, when an async function is used at the top level without explicit Promise handling, complexities arise.

Understanding Why It Doesn't Work

The issue here is that the main function returns a Promise, leaving the console.log('outside: ' text) statement stranded without a value to output immediately. The async/await syntax causes the 'inside' message to be logged after the 'outside' message because it waits for the Promise returned by main() to settle before proceeding.

Solving the Problem

To utilize the returned value without explicit then() handling, you have three options:

1. Top-Level Await in Modules

(Available in modern environments with ES2022 support)

const text = await main();
console.log(text);
Copy after login

2. Top-Level Async Function That Never Rejects

(async () => {
try {
const text = await main();
console.log(text);
} catch (e) {
// Handle Promise rejection or async exceptions here
}
})();
Copy after login

3. then and catch

main()
.then(text => {
console.log(text);
})
.catch(err => {
// Handle Promise rejection or async exceptions here
});
Copy after login

The above is the detailed content of Why Does `console.log` Appear Before Async Function Results in Top-Level `async` Code?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template