Sub topic 13
Top-Level await
This chapter assumes you know promises and async/await. It also assumes you have read the earlier chapters on running modules in Node.js and on how modules are linked and evaluated. The examples use .mjs files so Node.js treats them as ES modules without any extra configuration.
What Top-Level await Is
Top-level await lets you use await in the body of a module, outside any async function. The module pauses at that point, and any module that imports it waits until the awaited promise settles.
Before this feature, await was only valid inside an async function. A module that needed async setup had two options. It could wrap the work in an async function that runs immediately, or it could export a promise. Both put extra work on the importer. With top-level await, the module finishes its setup before anyone reads its exports.
// settings.mjs
import { setTimeout as delay } from 'node:timers/promises';
await delay(200); // stands in for reading a file or calling an API
export const settings = { theme: 'dark', retries: 3 };// main.mjs
import { settings } from './settings.mjs';
console.log(settings.retries); // 3, never undefinedRun it with node main.mjs. The console.log in main.mjs runs only after settings.mjs has finished its 200 ms wait.
Where It Is Allowed
Top-level await works only in ES modules. The same code fails elsewhere:
| Context | Top-level `await` |
|---|---|
| ES module (`.mjs`, `"type": "module"`, `<script type="module">`) | Allowed |
| Classic browser `<script>` | SyntaxError |
| CommonJS file (`.cjs`, or `.js` without `"type": "module"`) | SyntaxError |
| Inside a regular (non-async) function in a module | SyntaxError |
| Browser DevTools console, Node.js REPL | Allowed as a convenience |
for await (...) loops are also allowed at the top level of a module.
How It Changes Evaluation
In the lifecycle chapter, evaluation ran depth-first and was synchronous: each dependency ran to completion before the module that imported it. Top-level await makes a module asynchronous. The engine starts evaluating it, and when it reaches await it records that the module has not finished. Then it moves on.
Two rules follow:
- A module that imports an async module, directly or through other modules, does not run its body until the async module has finished.
- A sibling module that does not depend on the async module can run while the async module is paused.
The second rule is the one people get wrong. Here is a complete example.
// db.mjs
import { setTimeout as delay } from 'node:timers/promises';
console.log('db: connecting');
await delay(500);
console.log('db: ready');
export const db = {
query(sql) {
return `result of ${sql}`;
},
};// logger.mjs
console.log('logger: loaded');
export function log(message) {
console.log(`[log] ${message}`);
}// main.mjs
import { db } from './db.mjs';
import { log } from './logger.mjs';
log(db.query('SELECT 1'));Running node main.mjs prints:
db: connecting
logger: loaded
db: ready
[log] result of SELECT 1logger.mjs does not depend on db.mjs, so it runs while db.mjs waits. main.mjs depends on both, so it runs last.
If logger.mjs itself imported db.mjs, it would also wait, and logger: loaded would print after db: ready.
Common Uses
Initialization the module needs before exporting
Connecting to a resource, loading configuration, or fetching a WebAssembly binary are typical cases. Importers get finished values instead of promises.
Choosing a dependency at load time
Dynamic import() returns a promise, and top-level await lets you use that result as part of the module's setup. A common case is a fallback when an optional package is not installed:
// parser.mjs
let parse;
try {
({ default: parse } = await import('fast-json-parser'));
} catch {
parse = JSON.parse;
}
export { parse };Importers of parser.mjs always get a working parse function, whichever one was chosen.
Scripts and command-line tools
An entry-point script can await directly instead of defining async function main() and then calling it.
Comparing the Alternatives
// Alternative A: export a promise
export const ready = loadSettings(); // importers must write: await ready
// Alternative B: async IIFE
export let settings;
(async () => {
settings = await loadSettings(); // importers may read undefined
})();
async function loadSettings() {
return { theme: 'dark' };
}| Approach | Importer sees finished data | Blocks importers | Errors reach importers |
|---|---|---|---|
| Top-level `await` | Yes | Yes | Yes, the import fails |
| Export a promise | Only after its own `await` | No | Only if the importer awaits |
| Async IIFE | Only by chance of timing | No | No, unhandled rejection |
The async IIFE is the riskiest option. The live binding is undefined until the IIFE finishes, and nothing tells the importer when that happens. Exporting a promise is a good choice when importers should decide for themselves whether to wait.
Failure Modes
A rejected await fails the whole import
If the awaited promise rejects and nothing catches it, the module's evaluation fails. Every module that depends on it fails too. With a static import from the entry point, the program stops with the error. With dynamic import(), the returned promise rejects:
// broken.mjs
await Promise.reject(new Error('config missing'));
export const value = 1;// main.mjs
try {
await import('./broken.mjs');
} catch (error) {
console.log(error.message); // config missing
}The module map caches the failure. Importing broken.mjs again in the same process rejects with the same error and does not retry. If you need a retry, catch the error inside the module, or export a function that does the work.
A promise that never settles
If a top-level await never settles and nothing else keeps the process alive, Node.js exits with code 13 and prints a warning about an unsettled top-level await. In a browser, the dependent modules never run, and no error appears. A missing event or a fetch that hangs can cause this.
Deadlock through dynamic import
A module that awaits a dynamic import of a module that statically imports it back will wait forever:
// a.mjs
export const name = 'a';
await import('./b.mjs'); // b.mjs waits for a.mjs to finish, a.mjs waits for b.mjs// b.mjs
import { name } from './a.mjs';
console.log(name);Break the cycle by moving the shared values into a third module.
Slower startup
Each top-level await delays every module that depends on it. Putting a network request deep in a widely imported utility module delays the whole application. Keep awaits in modules close to the entry point, or start independent operations together with Promise.all.
CommonJS cannot wait
require() is synchronous. Recent Node.js versions can require() an ES module, but if that module's graph contains top-level await, the call throws ERR_REQUIRE_ASYNC_MODULE. Libraries meant for CommonJS consumers should avoid top-level await in their public entry points.
Exercises
Exercise
main.mjs contains import './a.mjs'; import './b.mjs'; console.log('main');. a.mjs contains console.log('a start'); await null; console.log('a end');. b.mjs contains import './a.mjs'; console.log('b');. What does node main.mjs print, and why?
Show answer
It prints "a start", "a end", "b", "main". b.mjs depends on a.mjs, so it cannot run until a.mjs finishes, even though await null resolves almost immediately. main.mjs runs last because it depends on both.
Exercise
A team loads feature flags with an async IIFE that assigns export let flags once a fetch completes. Some importers read flags as undefined. Rewrite the module using top-level await, and explain one cost of the change.
Show answer
Write const response = await fetch('/flags.json'); export const flags = await response.json();. Every importer now gets the loaded object. The cost is that every module depending on this one, directly or indirectly, waits for the fetch, which delays startup. If the fetch rejects, those imports fail.