Error Handling in Top-Level Await
You'll learn how uncaught promise rejections behave when await is used at the top level of a module, and why proper error handling is critical.
Understanding the Risk
When you use await at the top level of a module (outside any function), you're essentially making that module's entire execution async. If the awaited promise rejects and you don't handle it with try/catch, the error becomes an uncaught promise rejection that prevents the module from loading successfully.
Think of it like this: your module is a gatekeeper. If the gatekeeper encounters an error they can't handle, they refuse to open the gate entirely—your module fails to load, and anything depending on it also fails.
The Behavior
// module.js - DANGER: Unhandled rejection
const data = await fetch('/api/data').then(r => r.json());
// If fetch fails, the entire module fails to load
Unlike errors in regular async functions (which create rejected promises you can catch later), top-level await errors happen during module evaluation. There's no "later"—the module either loads or it doesn't.
Proper Error Handling
Always wrap risky top-level awaits in try/catch:
// module.js - SAFE
let data = null;
try {
data = await fetch('/api/data').then(r => r.json());
} catch (error) {
console.error('Failed to load data:', error);
data = { /* fallback defaults */ };
}
export { data };
This ensures your module can still load and export something, even if the async operation fails.
Key Takeaway: Uncaught promise rejections in top-level await prevent your entire module from loading—always use try/catch to handle potential failures gracefully and ensure your module remains usable.