Course contentsShow
← JavaScript
Lesson 1379 of 2,72330. Async/AwaitFree lesson

Top-Level Await for Resource Initialization

Waiting for database connections, config files, or APIs before module exports are available.

Top-Level Await for Resource Initialization

What you'll learn: How to use top-level await to ensure critical resources like databases, configuration files, or API connections are ready before your module exports become available.

The Problem It Solves

Imagine importing a module that needs to connect to a database before it can work properly. Without top-level await, you'd have to export a promise or force every user of your module to call an initialization function first. Top-level await lets you handle this setup inside the module itself, blocking exports until everything is ready.

How It Works

Top-level await pauses module execution at the top level (outside any function) until a promise resolves. This means dependent modules won't receive your exports until your async initialization completes.

// database.js
const connection = await connectToDatabase('mongodb://localhost');
const config = await fetch('/api/config').then(r => r.json());

export const db = connection;
export const appConfig = config;

When another module imports database.js, it won't proceed until both the database connection and config fetch have finished. The importing module automatically waits—no callbacks or init functions needed.

Real-World Pattern

// api-client.js
const apiKey = await fetch('/secrets/api-key').then(r => r.text());

export function callAPI(endpoint) {
  // apiKey is guaranteed to be available here
  return fetch(endpoint, {
    headers: { 'Authorization': apiKey }
  });
}

Any module importing callAPI knows it's ready to use immediately—the async initialization is already done.

The Guarantee

Top-level await ensures your module's contract: "When you import me, I'm fully initialized and ready." No race conditions, no manual setup steps, no "did you remember to call init()?" bugs.

Key Takeaway: Top-level await blocks module exports until critical async resources (databases, configs, API keys) are ready, guaranteeing safe, immediate use by importing modules.