Sub topic 3
How Top-Level Await Changes Evaluation Order
This chapter assumes you know static import/export, promises with async/await, and the earlier chapter on import().
Evaluation Order with Top-Level Await
Top-level await lets a module use await outside any function. When a module awaits at the top level, its evaluation pauses. Every module that imports it, directly or indirectly, also waits. Modules that do not depend on it keep evaluating, so one slow module does not stop its unrelated siblings.
Practical Patterns
- Initialization: fetch configuration once, then export it ready to use.
- Optional dependencies: try
await import()and fall back if the import fails.
let sharp = null;
try {
sharp = (await import('sharp')).default;
} catch {
console.warn('Optional dependency "sharp" is not installed; image resizing disabled');
}
export function canResize() {
return sharp !== null;
}Pitfalls: Startup Cost, Cycles, and Deadlocks
- Startup cost: a slow
awaitnear the root of the graph delays the whole app. Put anawaitat the top level only when importers really need the result before they run. - Deadlocks: suppose
a.jsrunsawait import('./b.js')andb.jsstatically importsa.js. Modulebwaits forato finish evaluating, andawaits forb. Neither finishes, and nothing throws.
Loading ES Modules from CommonJS
A CommonJS file cannot use top-level await. It can still call import() inside an async function. Newer Node.js versions also allow require() of an ES module, but only when that module's graph has no top-level await. If it does, Node throws ERR_REQUIRE_ASYNC_MODULE.
// main.cjs
async function main() {
const { greet } = await import('./greet.mjs');
console.log(greet('world'));
}
main();Import Attributes and JSON Modules
The second argument to import() carries import attributes. Passing type: 'json' tells the runtime to parse the file as JSON. The parsed data becomes the default export.
const { default: settings } = await import('./settings.json', {
with: { type: 'json' },
});
console.log(settings.theme);Exercise
main.js imports slow.js, which awaits a 3-second fetch at the top level, and fast.js, which has no await. When do fast.js and main.js evaluate?
Show answer
fast.js evaluates right away because it does not depend on slow.js. main.js evaluates only after slow.js finishes, roughly 3 seconds later, because a module runs only once all of its dependencies have finished evaluating.
Exercise
Why can't a CommonJS file use require() on an ES module that contains top-level await?
Show answer
require() is synchronous and must return the exports immediately. A module with top-level await finishes evaluating asynchronously, so Node throws ERRREQUIREASYNC_MODULE. Use await import() inside an async function instead.