JavaScript Async and Await
Mastering async/await syntax: synchronous-style asynchronous code, sequential vs parallel execution, and error handling with try/catch.
JavaScript Async and Await
async and await provide syntactic sugar over Promises, allowing developers to write asynchronous non-blocking code that reads sequentially like synchronous code.
1. Syntax Basics
- Adding
asyncbefore a function declaration ensures the function always returns a Promise. - The
awaitkeyword pauses function execution until the awaited Promise settles.awaitcan only be used insideasyncfunctions or at the top level of ES Modules.
async function loadUserData(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP Error ${response.status}`);
}
const user = await response.json();
return user;
} catch (error) {
console.error("Failed to load user:", error.message);
throw error; // Re-throw or return fallback
}
}2. Sequential vs. Parallel Execution Pitfall
β Anti-Pattern: Unintentional Sequential Waterfall
Awaiting independent promises sequentially doubles total network wait time:
// Total time = 1000ms + 1000ms = 2000ms
async function loadDashboardWaterfall() {
const user = await fetchUser(); // Takes 1000ms
const stats = await fetchAnalytics(); // Takes 1000ms (waited unnecessarily for user!)
return { user, stats };
}β
Best Practice: Parallel Execution with Promise.all
// Total time = Math.max(1000ms, 1000ms) = 1000ms
async function loadDashboardParallel() {
const [user, stats] = await Promise.all([
fetchUser(),
fetchAnalytics(),
]);
return { user, stats };
}3. Top-Level await (ES Modules)
In modern ES Modules, you can use await directly in module scope without wrapping it in an async function:
// config.js
const res = await fetch("https://api.example.com/remote-config");
export const remoteConfig = await res.json();Related Topics
JavaScript Promises and Asynchronous State
Mastering JavaScript Promises: pending/fulfilled/rejected states, then/catch/finally chaining, Promise.all, Promise.allSettled, and Promise.race.
JavaScript Error Handling (try, catch, throw, Error)
Mastering error handling in JavaScript: try/catch/finally blocks, standard Error subclasses (TypeError, SyntaxError), custom error classes, and unhandled rejections.