Course contentsShow
← JavaScript
Lesson 1980 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Module Loading with Top-Level Await

Modules using top-level await block their importers until the awaited promise settles.

Module Loading with Top-Level Await

You'll learn: How top-level await affects the loading order and timing of ES modules.

The Blocking Nature of Top-Level Await

When you use await at the top level of a module, you're not just pausing that module—you're creating a dependency that affects everything importing it. The module using top-level await blocks its importers until the awaited promise settles (resolves or rejects).

Think of it like a traffic light: If Module A imports Module B, and Module B has a top-level await, then Module A must wait at the intersection until Module B's promise turns green. The importing module cannot execute until the awaited operation completes.

How It Works

// database.js
const connection = await connectToDatabase();
export default connection;

// app.js
import db from './database.js';  // ← This import won't complete...
console.log('App started');      // ← ...until database.js finishes awaiting

In this example, app.js cannot proceed past the import statement until connectToDatabase() resolves. The entire import chain pauses.

The Ripple Effect

This blocking behavior cascades upward through the dependency graph. If Module C imports Module B, which imports Module A (which has top-level await), then Module C must wait for Module A's promise to settle before it can execute.

This ensures predictable initialization order but can create bottlenecks if awaited operations are slow or fail. Understanding this blocking behavior is crucial for managing application startup performance.

Key Takeaway: Top-level await blocks all importing modules until the awaited promise settles, creating a synchronous-like dependency chain in the module graph.