v8 recently introduced top-level await for ES modules. It’s a new proposed standard for ECMAScript, which has reached stage 3.

Note: it’s going to take some time before this feature will be usable in the production Node.js and in Chrome, but it’s worth taking a look

Right now we can use await only inside async functions. So it’s common to declare an immediately invoked async function expression to wrap it:

(async () => {
await fetch(/* ... */)
})()


or also declare a function and then call it:

const doSomething = async () => {
await fetch(/* ... */)
}

doSomething()


Top-level await will allow us to simply run

await fetch(/* ... */)


without all this boilerplate code.

With a caveat: this only works in ES modules. You can’t use this syntax outside of ES modules.

Normal scripts, and CommonJS modules, will continue to use immediately invoked function expressions or creating ad-hoc function like always.