Home > Web Front-end > JS Tutorial > Why Doesn't Top-Level Async/Await Work in JavaScript and How Can I Fix It?

Why Doesn't Top-Level Async/Await Work in JavaScript and How Can I Fix It?

DDD
Release: 2024-12-07 10:05:17
Original
743 people have browsed it

Why Doesn't Top-Level Async/Await Work in JavaScript and How Can I Fix It?

Using async/await at the Top Level

Question:

Why does the following code not work?

async function main() {  
    var value = await Promise.resolve('Hey there');
    console.log('inside: ' + value);
    return value;
}

var text = main();  
console.log('outside: ' + text);
Copy after login

Answer:

The reason the code doesn't work is because main returns a promise. All async functions return promises.

To use async/await at the top level, there are three options:

1. Top-Level await in Modules:

In ES2022, top-level await can be used in modules. This allows you to use await syntax at the top of the module. However, the module will not finish loading until the promise you await settles. If the promise is rejected, the module will fail to load.

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

2. Top-Level async Function That Never Rejects:

Use a top-level async function that never rejects (unless you want "unhandled rejection" errors):

(async () => {
    try {
        const text = await main();
        console.log(text);
    } catch (e) {
        // Handle errors
    }
})();
Copy after login

3. then and catch:

Use .then() and .catch() to handle the promise returned by main:

main()
    .then(text => {
        console.log(text);
    })
    .catch(err => {
        // Handle errors
    });
Copy after login

Note that all three options require handling promise rejections or async exceptions, as there is no caller to pass them on to.

The above is the detailed content of Why Doesn't Top-Level Async/Await Work in JavaScript and How Can I Fix It?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template