Sub topic 10
Top-Level Await in ES Modules
This chapter assumes you know ES module import/export syntax, can write async functions with await, and know how to make a file run as a module (type="module" in browsers, .mjs or "type": "module" in Node.js).
What Top-Level Await Is
Top-level await lets you use the await keyword directly in a module's body, outside any async function. Before it existed, await was only valid inside async functions. That rule forced awkward wrappers whenever a module needed asynchronous setup:
// The old workaround: an async IIFE
let config;
(async () => {
const response = await fetch('/config.json');
config = await response.json();
})();
export { config }; // may still be undefined when another module reads itThe problem with this wrapper is timing. The module finishes evaluating right away, so any module that imports config can read it before the fetch completes.
The Modern Form
With top-level await, the module itself waits:
// config.js
const response = await fetch('/config.json');
export const config = await response.json();// main.js
import { config } from './config.js';
console.log(config.apiUrl); // runs only after config.js has finished evaluatingWhen the runtime reaches an await in config.js, it pauses that module's evaluation. Every module that imports config.js, directly or indirectly, waits too. By the time main.js runs its first line, config holds the parsed JSON.
Where It Works and Where It Does Not
Top-level await is valid only in ES modules. A classic script or a CommonJS file reports a SyntaxError if it contains a top-level await.
| Context | Top-level await allowed? |
|---|---|
| `<script type="module">` | Yes |
| Classic `<script>` | No |
| Node.js `.mjs` file | Yes |
| Node.js `.js` with `"type": "module"` | Yes |
| Node.js `.cjs` or CommonJS `.js` | No |
| Web worker created with `{ type: 'module' }` | Yes |
Combining It with import()
Top-level await and import() fit together well. import() returns a promise, and top-level await lets a module settle that promise before it exports anything:
// renderer.js
const useWebGL = typeof WebGL2RenderingContext !== 'undefined';
const { draw } = useWebGL
? await import('./webgl-draw.js')
: await import('./canvas-draw.js');
export { draw };Modules that import draw from renderer.js always receive a working function. They never need to know which backend was chosen or when it loaded.
Common Mistakes
- Expecting it in an ordinary function.
awaitinside a non-asyncfunction is still a syntax error. Top-level await only applies to the module body. - Awaiting independent work one step at a time. Two unrelated
awaits in a row run one after the other. UsePromise.allwhen the operations do not depend on each other. - Forgetting that a rejection fails the module. If a top-level
awaitrejects and nothing catches it, the module fails to evaluate. Every importer then fails as well. Wrap risky awaits intry/catchwhen a fallback makes sense. - Using it for slow, optional work. Every importer waits for the module, so a slow top-level fetch delays the whole dependency chain.
Exercise
A file db.js contains export const db = await connect(); and is loaded with require('./db.js') from a CommonJS file. What happens, and how do you fix it?
Show answer
The require() call fails. Top-level await is only valid in ES modules: if db.js is treated as CommonJS, Node.js reports a SyntaxError, and if it is an ES module, require() throws ERRREQUIREASYNC_MODULE because it cannot wait for asynchronous evaluation. The fix is to load it from an async function in the CommonJS file with const { db } = await import('./db.js');, or to convert the importing file to an ES module.
Exercise
Module A uses const a = await fetchA(); const b = await fetchB(); where the two fetches are independent. How long do importers of A wait, and how can you shorten that?
Show answer
Importers wait for the sum of both fetch times, because the second fetch starts only after the first finishes. Write const [a, b] = await Promise.all([fetchA(), fetchB()]); so both run at the same time and importers wait only as long as the slower fetch.