Understanding Async/Await in JavaScript

Async/await didn’t add any new capability to JavaScript — it’s syntactic sugar over Promises — but it made asynchronous code readable enough that the old “callback hell” pattern from the Node.js early days is now genuinely rare in modern codebases.

From Callbacks to Promises to Async/Await

// The old way: callback hell
getUser(id, (user) => {
    getOrders(user.id, (orders) => {
        getOrderDetails(orders[0].id, (details) => {
            console.log(details); // three levels deep and still growing
        });
    });
});

// Promises: flatter, but still verbose
getUser(id)
    .then(user => getOrders(user.id))
    .then(orders => getOrderDetails(orders[0].id))
    .then(details => console.log(details));

// Async/await: reads like synchronous code
async function showFirstOrderDetails(id) {
    const user = await getUser(id);
    const orders = await getOrders(user.id);
    const details = await getOrderDetails(orders[0].id);
    console.log(details);
}

Error Handling with try/catch

async function fetchUserSafely(id) {
    try {
        const response = await fetch(<code>/api/users/${id}</code>);
        if (!response.ok) throw new Error(<code>HTTP ${response.status}</code>);
        return await response.json();
    } catch (error) {
        console.error('Failed to fetch user:', error);
        return null;
    }
}

The Trap: Sequential Awaits That Should Be Parallel

// Slow: each await blocks the next one, even though they're independent
const user = await fetchUser(id);
const posts = await fetchPosts(id);       // waits for fetchUser to finish first
const comments = await fetchComments(id); // waits for fetchPosts too

// Fast: run all three requests concurrently
const [user2, posts2, comments2] = await Promise.all([
    fetchUser(id),
    fetchPosts(id),
    fetchComments(id),
]);

This is the single most common async/await performance mistake — awaiting independent operations one at a time instead of firing them concurrently with Promise.all, turning what should be one round-trip’s worth of latency into three.