JavaScript
Write synchronous-looking asynchronous code with async, await, try/catch, and parallel execution.
Async / Await in Simple Terms
Introduced in ES2017 (ES8), async and await are syntactic sugar built on top of Promises. They allow you to write asynchronous code that reads sequentially like normal line-by-line synchronous code, eliminating complex .then() chains.
Think of cooking dinner in your kitchen:
- The Async Recipe: Marking a function as
asynctells JavaScript: "This recipe involves waiting for appliances." - The Await Pause: When you hit
await microwave(2), that specific recipe pauses until the microwave "Ding!" sounds. - Non-Blocking: While that recipe pauses, the main chef (JavaScript thread) is completely free to wash dishes, greet guests, and handle user clicks without freezing!
The Core Rules of Async / Await
Always Returns a Promise
Any async function wraps its return value in Promise.resolve() automatically.
await Pauses Execution
await can only be used inside async functions or top-level modules.
Clean try...catch
Rejected promises throw exceptions that can be caught using standard try...catch.
Writing Clean Async Code
function fetchUserData(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: "Aman", role: "Developer" });
else reject(new Error("Invalid User ID"));
}, 100);
});
}
async function displayUserProfile(id) {
try {
console.log("1. Starting profile fetch...");
const user = await fetchUserData(id);
console.log("2. User received:", user.name, "-", user.role);
return user.name;
} catch (error) {
console.error("2. Error handled:", error.message);
} finally {
console.log("3. Fetch attempt completed.");
}
}
displayUserProfile(101);
1. Starting profile fetch... 2. User received: Aman - Developer 3. Fetch attempt completed.
Sequential vs Parallel (The Waterfall Trap)
One of the most common mistakes in frontend development is awaiting independent promises sequentially instead of running them concurrently with Promise.all.
// ❌ SLOW: Waterfall (Total Time = 200ms + 200ms = 400ms)
async function fetchSequential() {
const users = await fetchUsers(); // waits 200ms
const products = await fetchProducts(); // then waits 200ms
}
// ✅ FAST: Parallel (Total Time = max(200ms, 200ms) = 200ms)
async function fetchParallel() {
const [users, products] = await Promise.all([fetchUsers(), fetchProducts()]);
}
Hands-On Practice: Fetch All User Records in Parallel
Write an async function loadAllUsers(ids) that fetches all user objects in parallel using Promise.all and map().