Home >Web Front-end >JS Tutorial >How Do I Properly Execute Asynchronous Code at the Top Level in JavaScript?
In asynchronous programming, the async/await feature allows you to switch between synchronous and asynchronous tasks seamlessly. However, when executing asynchronous code at the top level, certain considerations must be made.
When you define an async function, it returns a Promise. When you call this function at the top level, it immediately returns the Promise, not the resolved value. This is why your console outputs the Promise object before it executes the asynchronous task.
To solve this, you have several options:
1. Top-level Await (ES2022 Proposal)
In modern environments, you can use top-level await in modules. This allows you to await a Promise directly in the module scope.
const text = await main(); console.log(text); // Logs the resolved value
2. Top-level Async Function with Unhandled Rejection
You can define a top-level async function that never rejects. This prevents unhandled rejection errors but doesn't handle errors explicitly.
(async () => { try { const text = await main(); console.log(text); // Logs the resolved value } catch (e) { // Error handling (optional) } })();
3. then() and catch()
If neither of the above options is suitable, you can use the Promise's then() and catch() methods to handle the result.
main() .then((text) => { console.log(text); // Logs the resolved value }) .catch((err) => { // Error handling });
Note: In all cases, it's important to handle rejections properly to prevent unhandled rejection errors.
The above is the detailed content of How Do I Properly Execute Asynchronous Code at the Top Level in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!