JavaScript › ES Modules

How does top-level await work, and what constraint does it place on modules that import that module?

Advanced

Answer

Top-level await lets a module pause its own evaluation until a Promise resolves, without wrapping code in an async function. Any module that imports a module using top-level await will itself wait for that import to finish resolving before continuing.
// config.js
const response = await fetch('/config.json');
export const config = await response.json();

// main.js — implicitly waits for config.js to finish
import { config } from './config.js';
Real-world example Loading remote configuration once at module initialization time before the rest of the app starts using it.

Common follow-ups: Why was top-level await NOT allowed in CommonJS modules?