JavaScript Async/Await
async and await are syntax built on top of promises that lets you write asynchronous code that reads like ordinary, top-to-bottom code. No .then() chains, no nested callbacks — and errors are handled with the familiar try…catch.
async functions
Putting async before a function does two things:
- The function always returns a promise. A returned value becomes the fulfilled value; a thrown error becomes a rejection.
- Inside it, you can use
await.
async function getNumber() {
return 42;
}
async function fail() {
throw new Error("nope");
}
console.log(getNumber()); // a promise, not 42 (still pending when logged)
getNumber().then((n) => console.log("value:", n));
fail().catch((err) => console.log("error:", err.message));Promise { <pending> }
value: 42
error: nope
await
await promise pauses the async function until the promise settles, then gives you its value (or throws its error). While the function is paused, the rest of the program keeps running — nothing is blocked:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function makeBreakfast() {
console.log("put toast in");
await wait(100);
console.log("toast done");
await wait(50);
console.log("coffee done");
return "breakfast ready";
}
makeBreakfast().then((msg) => console.log(msg));
console.log("(meanwhile, reading the news)");put toast in
(meanwhile, reading the news)
toast done
coffee done
breakfast ready
Promise chain vs async/await
Here's the same sequence from the Promises chapter, rewritten. Each step waits for the previous one, but the code is flat and uses normal variables:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function fetchUser(id) {
await wait(30);
return { id, name: "Mina" };
}
async function fetchOrders(user) {
await wait(30);
return [`order-1 for ${user.name}`, `order-2 for ${user.name}`];
}
async function showDashboard() {
try {
const user = await fetchUser(1);
console.log("user:", user.name);
const orders = await fetchOrders(user);
console.log("orders:", orders.length);
console.log("first:", orders[0]);
} catch (err) {
console.log("failed:", err.message);
} finally {
console.log("done");
}
}
await showDashboard(); // top-level await works in modulesuser: Mina
orders: 2
first: order-1 for Mina
done
Playgrounds run as ES modules, so you can use await at the top level, outside any function. In classic scripts, await is only allowed inside async functions.
Error handling with try…catch
A rejected promise makes await throw, so ordinary try…catch handles asynchronous errors:
async function loadConfig(name) {
await null; // pretend to do some async work
if (name !== "app.json") throw new Error(`${name} not found`);
return { theme: "dark" };
}
for (const file of ["app.json", "missing.json"]) {
try {
const config = await loadConfig(file);
console.log(file, "->", config);
} catch (err) {
console.log(file, "->", err.message);
}
}app.json -> { theme: 'dark' }
missing.json -> missing.json not found
Sequential vs parallel
A common mistake is awaiting independent tasks one by one, making them run sequentially. If they don't depend on each other, start them all first and await them together with Promise.all:
const log = [];
const task = (name, ms) =>
new Promise((resolve) => {
log.push(`start ${name}`);
setTimeout(() => {
log.push(`end ${name}`);
resolve(name);
}, ms);
});
// sequential: B doesn't even start until A has finished (~400 ms total)
await task("A", 200);
await task("B", 200);
console.log("sequential:", log.join(" → "));
log.length = 0;
// parallel: both start immediately (~200 ms total)
const results = await Promise.all([task("C", 200), task("D", 200)]);
console.log("parallel: ", log.join(" → "));
console.log(results);sequential: start A → end A → start B → end B
parallel: start C → start D → end C → end D
[ 'C', 'D' ]
Common pitfalls
| Pitfall | Fix |
|---|---|
Forgetting await — you get a Promise object instead of the value |
add await (and make the function async) |
await inside forEach doesn't wait |
use for…of, or Promise.all(arr.map(async …)) |
| Awaiting independent tasks one by one | start them together, then await Promise.all([...]) |
No try…catch around awaits |
unhandled rejections crash Node and log errors in browsers |
// ❌ forEach ignores the returned promises
ids.forEach(async (id) => await save(id));
// ✅ one after another
for (const id of ids) await save(id);
// ✅ all at once
await Promise.all(ids.map((id) => save(id)));Test yourself
What does an async function always return?
- The returned value directly
- A promise
- undefined
- A callback
How do you handle a rejected promise when using await?
- With .then()
- With try…catch
- Errors can't happen with await
- With if (err)
Two independent requests each take 1 second. How long does await Promise.all([r1(), r2()]) take?
- About 1 second
- About 2 seconds
- 0 seconds
- It depends on the order