Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readJavaScript

Top-level await and module load order

Trace how top-level await delays dependent modules while an independent branch of the import graph runs.

You put an await at the top of one module. Now the logs from your other modules come out in an order you did not expect. Some run before the awaiting module finishes. One waits for it.

Four files show the rule. main.mjs imports b.mjs and then a.mjs. Both of those import c.mjs, and b.mjs has a top-level await.

// main.mjs
import './b.mjs'
import './a.mjs'
console.log('main.mjs')

// a.mjs
import './c.mjs'
console.log('a.mjs')

// b.mjs
import './c.mjs'
console.log('b.mjs before await')
await new Promise((resolve) => setTimeout(resolve, 100))
console.log('b.mjs after await')

// c.mjs
console.log('c.mjs')

Save each section as the named file in one folder and run node main.mjs. The .mjs extension tells Node to use ES modules. The output has a line from a.mjs between the two lines of b.mjs.

c.mjs
b.mjs before await
a.mjs
b.mjs after await
main.mjs

diagram

Which module prints when, with one top-level await

The module graph with the order each line prints, 1 to 5, on the node that prints it.

Read the order from the graph

Read this acyclic graph using two rules.

  • Module evaluation visits static dependencies depth first in import order and evaluates each shared module once.
  • A module with a top-level await pauses there, and the modules that import it wait.

The first rule gives c.mjs first, because it sits at the bottom of the first path. Then b.mjs runs until it reaches its await, where it pauses.

Here b.mjs is suspended, so the loader moves on to a.mjs. a.mjs does not import b.mjs, so nothing holds it back, and it prints third.

main.mjs imports b.mjs, so it cannot start until b.mjs finishes. When the timer fires, b.mjs prints its second line, and main.mjs runs last.

Two variations

I removed the await and its line from b.mjs and ran the graph again. The output was c.mjs, b.mjs, a.mjs, main.mjs. Plain imports finish one module at a time, so a.mjs waits its turn.

Then I put the await back and swapped the two imports in main.mjs, so a.mjs comes first. The output was c.mjs, a.mjs, b.mjs before await, b.mjs after await, main.mjs. Import order still decides who starts first, and main.mjs is still last.

If your logs look shuffled, draw the import graph on paper and mark the module with the await. In an acyclic module graph, direct and indirect importers wait for the awaited work. A sibling can run while it waits as long as that sibling has no pending dependency.