0
0
JavascriptConceptBeginner · 3 min read

Top Level Await in JavaScript: What It Is and How It Works

In JavaScript, 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.

javascript
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!');
Output
Start waiting... 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.

Key Takeaways

Top level await lets you use await outside async functions in ES modules.
It pauses module execution until the awaited promise finishes.
Use it to simplify asynchronous setup like fetching data or loading resources.
It only works in modules, not in regular script files.
Avoid overusing it to prevent blocking your app's startup.