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.

💡 Real-World Analogy: The Kitchen Microwave Timer

Think of cooking dinner in your kitchen:

  • The Async Recipe: Marking a function as async tells 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

01

Always Returns a Promise

Any async function wraps its return value in Promise.resolve() automatically.

02

await Pauses Execution

await can only be used inside async functions or top-level modules.

03

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);
Output
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()]);
}
🎯 Async / Await Interview Deck
Question 1 of 5
JavaScript Interview PuzzleQ1 of 5
async function getAnswer() {
    return 42;
}
const result = getAnswer();
console.log(result);
What is stored in the variable 'result'?
JavaScript Interview PuzzleQ2 of 5
async function loadData() {
    try {
        const res = await Promise.reject(new Error("Network Outage"));
        console.log("Loaded:", res);
    } catch (err) {
        console.log("Caught:", err.message);
    }
}
loadData();
What will be printed to the console?
JavaScript Interview PuzzleQ3 of 5
async function processItems() {
    const items = [1, 2, 3];
    for (const num of items) {
        await new Promise(r => setTimeout(r, 10));
        console.log(num);
    }
}
processItems();
How will the numbers be logged?
JavaScript Interview PuzzleQ4 of 5
async function testForEach() {
    [1, 2, 3].forEach(async (num) => {
        await new Promise(r => setTimeout(r, 20));
        console.log(num);
    });
    console.log("Done!");
}
testForEach();
What will be logged first?
JavaScript Interview PuzzleQ5 of 5
const delay = ms => new Promise(r => setTimeout(r, ms));

async function runParallel() {
    const start = Date.now();
    await Promise.all([delay(100), delay(50)]);
    console.log("Total elapsed:", Math.round((Date.now() - start) / 100) * 100);
}
runParallel();
What will be the approximate total elapsed time?

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().