Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
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 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 |