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

When to Use vs Avoid Top-Level Await

Deciding whether to initialize asynchronously at the top level or defer with lazy patterns.

When to Use vs Avoid Top-Level Await

You'll learn when top-level await is the right tool and when it creates more problems than it solves.

The Decision Point

Top-level await lets you block module loading until async operations complete. This is powerful, but it fundamentally changes how your module behaves in the dependency graph. The key question: Should this initialization block everything else, or can it happen lazily?

When to Use Top-Level Await

Use it when:

  • The module genuinely can't function without the data (like essential config or feature flags)
  • You're loading critical resources that every consumer needs immediately
  • You want to fail fast during startup rather than discovering missing data later

Think of it like checking your keys before leaving home—better to pause now than discover you're locked out later.

When to Avoid Top-Level Await

Avoid it when:

  • The async operation is slow or might fail (don't make every importer wait)
  • Only some consumers need the data (let them request it when needed)
  • You're building a library (don't control your users' load times)
  • The operation can reasonably be deferred until first use

The Lazy Pattern Alternative

Instead of initializing at the top level, export a function that awaits on first call and caches the result. This keeps your module fast to import and lets consumers control when the cost is paid.

// ❌ Blocks every importer
const data = await fetchHeavyData();

// ✅ Deferred until needed
let cache;
export async function getData() {
  if (!cache) cache = await fetchHeavyData();
  return cache;
}

Key Takeaway: Use top-level await only for truly essential, fast initialization that every consumer needs—otherwise, prefer lazy loading patterns that don't block the entire module graph.