Sub topic 13
Top-Level await
This chapter assumes you know how promises and async/await work, and that you have seen how modules are linked and evaluated. Top-level await lets a module use await outside any function. The module pauses its own evaluation until the promise settles. Any module that imports it also waits.
Before and After
Before top-level await, a module that needed async setup had two options. It could export a promise, which forced every importer to await it. Or it could wrap the setup in an async function and export values that were not ready yet. With top-level await, the module finishes its async work first, and importers receive values that are ready to use.
// data.js
console.log('data.js: start');
export const user = await new Promise((resolve) => {
setTimeout(() => resolve({ name: 'Ada' }), 100);
});
console.log('data.js: done');// main.js
import { user } from './data.js';
console.log('main.js:', user.name);Running node main.js in a package with "type": "module" prints:
data.js: start
data.js: done
main.js: Adamain.js does not run until data.js has finished evaluating. That includes its await. So user is always defined when main.js reads it.
Where It Works
| Context | Top-level `await` allowed? |
|---|---|
| ES module (`type="module"`, `.mjs`, `"type": "module"`) | Yes |
| Classic `<script>` | No, it is a SyntaxError |
| CommonJS file (`.cjs`) | No |
| Inside a non-async function | No |
Common Errors
- Blocking the whole graph. Every module that depends on the waiting module is delayed, directly or through other imports. A slow network request at the top level of a shared module delays application startup. Keep top-level awaits short, or move slow work behind a function that callers invoke when they need it.
- Unhandled rejections. If the awaited promise rejects, the module fails to evaluate. Every static import of it fails too. Use
try/catchwhen a fallback makes sense:
// storage.js
let backend;
try {
backend = await import('./indexeddb-backend.js');
} catch {
backend = await import('./memory-backend.js');
}
export default backend.default;- Requiring it from CommonJS. In recent Node.js versions,
require()can load a synchronous ES module. If that module's graph uses top-levelawait,require()throwsERR_REQUIRE_ASYNC_MODULE. Useawait import()from the CommonJS side instead. - Deadlocks in cycles. If two modules in a circular dependency each wait for a value the other provides, neither one finishes. Break the cycle before you add top-level
await.
Exercise
A module config.js has export const settings = await loadSettings();, and loadSettings() rejects. What happens to app.js, which has import { settings } from './config.js';?
Show answer
app.js never runs. config.js fails to evaluate because the awaited promise rejected. The error spreads to every module that imports it, so loading app.js fails with that same error.
Exercise
Why is await fetch('/huge-dataset.json') at the top level of a widely imported utils.js a poor choice?
Show answer
Every module that imports utils.js, directly or indirectly, has to wait for the download before it can evaluate. Startup is then delayed even for code that never uses the data. Export an async function that fetches the data on demand instead.