Top Level Await in JavaScript: What It Is and How It Works
top level await allows you to use the await keyword outside of async functions, directly in modules. This means you can pause execution at the top level of your code until a promise resolves, making asynchronous code simpler and more readable.How It Works
Normally, the await keyword can only be used inside functions marked as async. This means you have to wrap your asynchronous code inside a function to pause and wait for a promise to finish.
With top level await, you can use await directly in your JavaScript module without wrapping it in a function. Think of it like waiting for your coffee to brew before you start your day — you pause the whole script until the coffee (promise) is ready.
This feature works only in modules (files treated as ES modules) and lets your code run in a more straightforward way, especially when loading data or resources before continuing.
Example
This example shows how you can use await at the top level to wait for a promise that resolves after 2 seconds.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); console.log('Start waiting...'); await wait(2000); // Pause here for 2 seconds console.log('Done waiting!');
When to Use
Use top level await when you need to load data or perform asynchronous setup before the rest of your code runs. For example, fetching configuration from a server, loading modules dynamically, or reading files in Node.js.
This makes your code easier to read and avoids deeply nested async functions or callbacks. However, be careful because it pauses the entire module, which might delay other parts of your app if overused.
Key Points
- Top level await works only inside ES modules, not in regular scripts.
- It pauses the whole module until the awaited promise resolves.
- It simplifies asynchronous code by removing the need for extra async functions.
- Use it wisely to avoid blocking important code.