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.
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.
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);
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 } })();
3. then and catch
main() .then(text => { console.log(text); }) .catch(err => { // Handle Promise rejection or async exceptions here });
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!