Top-level await and dependency evaluation
How it works
Top-level await is available in ES module bodies. It can pause evaluation of a module while its awaited promise settles. Dependent modules that need its evaluation wait; unrelated modules may still make progress. A rejection becomes an evaluation failure. Avoid unnecessary startup waits and cycles involving promises that cannot settle.
Example 1
Save each file separately. Run with Node.js: main.mjs. This is a multi-file example, not a single editor snippet.
config.mjs
console.log("config start");export const rate = await Promise.resolve(4);console.log("config ready");main.mjs
Expected output in the tested environment:
config startconfig readyentry 4The dependent entry body waits for successful evaluation of its dependency.
Common mistake
Top-level await does not block the entire JavaScript host thread; it suspends the relevant module evaluation.
Practice
Replace the resolved promise with a rejected promise in the dependency. Load the entry using dynamic import from a new file and handle rejection.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Top-level await and dependency evaluation — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
Where can await be used without an enclosing async function in this chapter?
What happens to the dependent entry body in the example?
What is the consequence of an uncaught rejected top-level await?
Which design avoids needless startup blocking?
For Top-level await and dependency evaluation, what is the console output of example 1 in Node.js 22.16.0?
// File: config.mjsconsole.log("config start");export const rate = await Promise.resolve(4);console.log("config ready");
// File: main.mjsimport { rate } from "./config.mjs";console.log("entry", rate);