Skip to content
AgileLogics
5 min read

Async/Await

Prerequisites: Promises

async/await lets you write Promise-based code that reads like ordinary, top-to-bottom code, instead of chaining .then() calls.

async function getUser(id) {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) {
        throw new Error("User not found");
    }
    return response.json();
}

async function main() {
    try {
        const user = await getUser(1);
        console.log(user.name);
    } catch (error) {
        console.log("Failed:", error.message);
    }
}

await pauses the function (without blocking the rest of the program) until the Promise settles. A function containing await must itself be declared async.

Common mistakes

  • Forgetting await before an async call — you get the Promise object itself, not its resolved value.