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:

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

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

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

doSomething();

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

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.