/

How to Use Top-Level Await in JavaScript

How to Use Top-Level Await in JavaScript

Discover how to utilize the top-level await feature in JavaScript, which is currently available in v8.

Typically, you can only use await inside async functions. As a result, it’s common to declare an immediately invoked async function expression to wrap it:

1
2
3
(async () => {
await fetch(/* ... */);
})();

Alternatively, you can declare a function and then call it:

1
2
3
4
5
const doSomething = async () => {
await fetch(/* ... */);
};

doSomething();

However, with the introduction of top-level await, you can simply run:

1
await fetch(/* ... */);

without having to include all that boilerplate code.

There is a caveat, though: this feature only works in ES modules.

For a single JavaScript file, without a bundler, you can save it with the .mjs extension and then you can use top-level await.

tags: [“JavaScript”, “top-level await”]