Sub topic 11
How Top-Level Await Changes Evaluation Order
This chapter assumes you know static import/export, Promises with async/await, and how to run ES modules in Node.js (.mjs files or "type": "module") or a browser (<script type="module">). It also assumes you met top-level await in the previous chapter. Here the focus is narrower: when a module pauses at a top-level await, which other modules keep running, which ones wait, and in what order everything finishes.
The baseline: synchronous evaluation order
Without top-level await, a module graph is evaluated in post-order depth-first order. The runtime walks the imports of each module in the order they appear in the source. It evaluates each dependency fully before the module that imports it. Each module is evaluated at most once, even if many modules import it.
// a.js
console.log('a');
export const a = 'A';
// b.js
console.log('b');
export const b = 'B';
// main.js
import { a } from './a.js';
import { b } from './b.js';
console.log('main', a, b);Running node main.js (with "type": "module") prints a, b, main A B. Everything happens in one synchronous pass, so the order depends only on graph structure and import order.
What top-level await changes
A module that contains a top-level await becomes an async module. The runtime still visits the graph in the same depth-first order, and it still starts each module in that order. The difference shows up when an async module reaches an await:
- The async module's own evaluation pauses until the awaited promise settles.
- Every module that depends on it, directly or through a chain of imports, waits until it finishes.
- Modules that do not depend on it keep evaluating in their normal order.
The last point surprises people. Top-level await does not freeze the whole graph. It only blocks the modules that import the paused module.
Sibling modules keep running
Here is the earlier example with an async module in the first position.
// x.js
console.log('x: start');
await new Promise((resolve) => setTimeout(resolve, 100));
console.log('x: end');
export const x = 1;
// y.js
console.log('y: run');
export const y = 2;
// main.js
import { x } from './x.js';
import { y } from './y.js';
console.log('main', x, y);The output is:
x: start
y: run
x: end
main 1 2The runtime starts x.js first because it is imported first. The code before the await runs synchronously, so x: start prints. Then x.js pauses. y.js does not import x.js, so the runtime evaluates it right away. main.js depends on both modules, so it runs only after x.js resumes and finishes.
Dependents wait, even transitively
Now make y.js import x.js.
// y.js
import { x } from './x.js';
console.log('y: run, x =', x);
export const y = x + 1;With the same x.js and main.js, the output becomes:
x: start
x: end
y: run, x = 1
main 1 2y.js now depends on x.js, so it cannot start until x.js finishes. You never have to write await in y.js or main.js for this. The waiting comes from the import relationship. Importers also never see a half-initialized binding from an async module: by the time any code in y.js runs, x holds its final value.
This is also why one slow async module deep in a graph can delay every module above it. The pitfalls chapter returns to the startup cost this causes.
Async siblings run concurrently
When two independent dependencies are both async, the runtime starts the first, lets it pause, then starts the second. Their awaits overlap.
// slow-a.js
console.log('a: start');
await new Promise((resolve) => setTimeout(resolve, 200));
console.log('a: end');
export const a = 'A';
// slow-b.js
console.log('b: start');
await new Promise((resolve) => setTimeout(resolve, 200));
console.log('b: end');
export const b = 'B';
// main.js
const t0 = performance.now();
import { a } from './slow-a.js';
import { b } from './slow-b.js';
console.log(a, b, `${Math.round(performance.now() - t0)} ms after main started`);The log shows a: start, b: start, a: end, b: end, then the final line. The two waits overlap, so the total time is about 200 ms, not 400 ms.
The timing line in main.js measures almost nothing. Static imports are hoisted, so main.js body code, including t0, runs only after both dependencies finish. To measure the whole load, time it from outside, for example by running time node main.js in the shell.
The order of completion
Once several async modules are pending, completion follows a few rules:
- A module finishes evaluating only after all of its dependencies have finished.
- Among modules that become ready at the same moment, the runtime evaluates them in the same post-order it would use without top-level await.
- A module with no
awaitof its own still counts as "async" for its importers if it sits above an async module. It runs as soon as its dependencies are done.
Rule 2 keeps evaluation deterministic. If two modules both wait only on the same async module, they run in their original depth-first order once it finishes, whatever the timer or network timing.
| Situation | Does module M wait for async module A? |
|---|---|
| M imports A directly | Yes |
| M imports B, which imports A | Yes |
| M and A are siblings under the same parent | No, M runs while A is paused |
| M is the parent of both A and B | Yes, M waits for all of its dependencies |
| M loads A with `import()` inside a function | Only if M awaits that promise |
Dynamic import waits for the whole subgraph
The promise returned by import() resolves only after the target module and its whole dependency subgraph have finished evaluating, including any top-level awaits.
// db.js
console.log('db: connecting');
await new Promise((resolve) => setTimeout(resolve, 150));
console.log('db: connected');
export const db = { query: (sql) => `result of ${sql}` };
// app.js
console.log('app: before import');
const { db } = await import('./db.js');
console.log('app:', db.query('SELECT 1'));Output:
app: before import
db: connecting
db: connected
app: result of SELECT 1If app.js called import('./db.js') without awaiting it, app.js would finish right away, and db.js would complete later on its own. Statically imported dependencies always block their importer. Dynamically imported ones block only code that awaits the promise.
A second import('./db.js') returns a promise for the same module instance. If the first evaluation is still in progress, the second caller waits for that same evaluation. It does not start a new one.
Errors propagate up the graph
If an async module's top-level await rejects, or its code throws after resuming, that module's evaluation fails. Every module that depends on it also fails, and none of their bodies run.
// flaky.js
console.log('flaky: start');
await Promise.reject(new Error('config server unreachable'));
export const value = 42;
// user.js
import { value } from './flaky.js';
console.log('user: this never prints', value);
// entry.js
try {
await import('./user.js');
} catch (err) {
console.log('caught:', err.message);
}
try {
await import('./flaky.js');
} catch (err) {
console.log('caught again:', err.message);
}Output:
flaky: start
caught: config server unreachable
caught again: config server unreachableThe failure is cached. Importing flaky.js again does not retry evaluation. It rejects with the same error. If you need to retry, put the retry logic inside the module, before the await settles for good, or use a fresh specifier. The chapter on dynamic import failures covers fallback strategies.
Sibling modules that do not depend on the failed module may already have run. Their side effects are not rolled back, even though the parent module fails.
Summary of the model
- Modules still start in post-order depth-first order.
- An async module pauses only itself and the modules that depend on it.
- Independent siblings keep evaluating, and independent async siblings wait concurrently.
import()resolves after the target's entire subgraph has finished.- A rejection fails the module and all its dependents, and the failure is cached.
Exercise
main.js imports, in order, p.js and q.js. p.js logs "p1", awaits a 50 ms timer, then logs "p2". q.js imports nothing and logs "q". main.js logs "main". What is the output order?
Show answer
p1, q, p2, main. p.js starts first and runs until its await. q.js does not depend on p.js, so it runs while p.js is paused. main.js waits for both, so it runs last.
Exercise
Change q.js from the previous exercise so it imports p.js. What is the output order now, and why?
Show answer
p1, p2, q, main. q.js now depends on p.js, so it cannot evaluate until p.js has finished, including the code after its await.
Exercise
Two independent modules each await a 300 ms timer at top level, and main.js statically imports both. Roughly how long until main.js's body runs, and what would change if the second module imported the first?
Show answer
About 300 ms, because the runtime starts both and their waits overlap. If the second imported the first, its own timer would start only after the first finished, so the total would be about 600 ms.
Exercise
A module's top-level await rejects. Later, a different part of the app calls import() on the same specifier. What happens?
Show answer
The import() promise rejects with the same cached error. The module is not evaluated again, so the code before its await does not run a second time.