Asynchronous: Top-level await

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Usually you 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 allows us to simply run

await fetch(/* ... */)

without all this boilerplate code.

With a caveat: this only works in ES modules.

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

This is particularly useful when you need to load configuration, establish database connections, or perform other async initialization at the module level.

Lessons in this unit:

0: Introduction
1: Callbacks
2: Timers
3: Promises
4: Async functions
5: Chaining promises
6: Orchestrating promises
7: ▶︎ Top-level await
8: Async with array methods
9: Converting callbacks to async/await