Felipe Felipe - 3 years ago 228
Node.js Question

How can I use async/await at the top level?

I have been going over async/await in ES7 and after going over several articles, I decided to test things myself. However, I can't seem to wrap my head around why this does 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)


The console outputs the following (node v8.6.0) :


> outside: [object Promise]

> inside: Hey there


Why does the log message inside the function execute afterwards? I thought the reason async/await was created was in order to perform synchronous execution using asynchronous tasks.

Is there a way could I use the value returned inside the function without using a
.then()
after
main()
?

Answer Source

I can't seem to wrap my head around why this does not work.

Because main returns a promise; all async functions do.

At the top level, you must either use a top-level async function that never rejects, like this:

(async () => {
    try {
        var text = await main();
        console.log(text);
    } catch (e) {
        // Deal with the fact the chain failed
    }
})();

Notice the catch; you must handle promise rejections / async exceptions.

Or use then and catch:

main()
    .then(text => {
        console.log(text);
    })
    .catch(err => {
        // Deal with the fact the chain failed
    });

...or both arguments to then:

main().then(
    text => {
        console.log(text);
    },
    err => {
        // Deal with the fact the chain failed
    }
);

Again notice we're registering a rejection handler.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download