Promises and Async/Await

Site Admin · 11 Sep 2026 · 4 views

Promises and Async/Await

JavaScript runs code in a single thread but handles slow operations - network requests, file reads, timers - asynchronously. Promises and async/await manage this asynchrony cleanly.

Why Async Matters

A network request can take seconds. Blocking the main thread would freeze the page. Instead, JavaScript starts the request, continues running other code, and handles the result later. Callbacks did this first, but they led to callback hell. Promises and async/await fixed that.

Promises

// Creating a promise
const wait = (ms) => new Promise((resolve, reject) => {
    if (ms < 0) {
        reject(new Error("Invalid duration"));
        return;
    }
    setTimeout(resolve, ms);
});

// Consuming a promise
wait(1000)
    .then(() => console.log("Waited 1 second"))
    .catch((err) => console.error(err))
    .finally(() => console.log("Done"));

Async/Await

async/await makes asynchronous code read like synchronous code:

async function fetchUserProfile(userId) {
    try {
        const response = await fetch(`/api/users/${userId}`);
        if (!response.ok) {
            throw new Error("Request failed");
        }
        const user = await response.json();
        const posts = await fetch(`/api/users/${userId}/posts`);
        const userPosts = await posts.json();
        return {user, posts: userPosts};
    } catch (error) {
        console.error(error);
        return null;
    }
}

const profile = await fetchUserProfile(42);

Running Promises in Parallel

Promise.all runs multiple async operations concurrently:

async function loadAll() {
    const [users, products, orders] = await Promise.all([
        fetch("/api/users").then(r => r.json()),
        fetch("/api/products").then(r => r.json()),
        fetch("/api/orders").then(r => r.json())
    ]);
    return {users, products, orders};
}

// Promise.allSettled resolves even if some reject
const results = await Promise.allSettled([p1, p2, p3]);

An Async Timer

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function countdown() {
    for (let i = 5; i > 0; i--) {
        console.log(i);
        await delay(1000);
    }
    console.log("Go!");
}

Key Points

  • Promises represent the eventual result of an async operation.
  • Use then, catch, and finally to consume promises.
  • async functions always return a promise.
  • await pauses execution until a promise settles.
  • Promise.all runs async operations in parallel.
Share this post:

Comments (0)

Please login or register to comment.