Top-level await is a ECMAScript language feature that enables developers to use the await
keyword outside of async
functions. It acts like a big async
function causing other modules who import them to wait before they start evaluating their body.
As of May 2021, all major browsers and NodeJS support Top-level await.
Example
await Promise.resolve(console.log(''));
Without top-level await support, the above line produces the following error:
SyntaxError: await is only valid in async function
Workaround
Without top-level await support, the below boilerplate would typically be used by developers to workaround the lack of top-level await support.
(async function() {
await Promise.resolve(console.log(''));
}());
History
The proposal for this ECMAScript language feature was initially submitted in January 2018 by Myles Borins and reached TC39 Stage 4 in May 2021.
All major browsers added support for this feature in the beginning of 2021. NodeJS added experimental support for this feature in 14.3.0 and full support in 14.8.0.