Explain it simply
Async/await in plain language
Async/await is not a new kind of Promise; it is a more readable way to write code that uses Promises. Instead of chaining then callbacks, you write code that reads from top to bottom. You mark a function with async, and wherever you need the result of a Promise, you write await in front of it.
Picture ordering at a coffee shop and waiting by the counter. You are waiting, but the barista keeps serving other customers. await works the same way: one async function pauses and waits, while the JavaScript engine keeps running everything else.
Problem → Why → Solution
The problem: forEach does not wait
You want to save three orders and then show 'all saved'. Passing an async callback to forEach looks right, but 'all saved' prints before a single save has finished. If one save fails, the surrounding try/catch does not catch it either, and you get an unhandled rejection.
async function saveAll(orders) {
try {
orders.forEach(async (order) => {
await saveOrder(order); // forEach ignores the Promise this returns
});
console.log("all saved"); // prints immediately
} catch (error) {
console.error("save failed", error); // never reached for a failed save
}
}Why this happens
Each async callback returns a Promise, but forEach throws the callback's return value away, so nothing in saveAll ever awaits those Promises. To save one after another, use for...of with await; to save them all at once, use await Promise.all(orders.map(saveOrder)).
Core concept: async returns a Promise, await unwraps one
Putting async in front of a function makes it always return a Promise. Writing return "hi" gives a Promise fulfilled with "hi", and throw new Error("x") gives a Promise rejected with that error. So the caller must get the result with .then() or with await.
await promise pauses the current async function until the Promise settles. If it fulfils, the value becomes the result of the expression; if it rejects, the reason is thrown right at that line, which is why an ordinary try/catch can catch async errors. While the function is paused, the engine returns to the caller and keeps running other code, timers and events; the thread is never blocked.
await is only allowed inside an async function, with two exceptions: the top level of an ES module and the browser DevTools console. At the top level of a CommonJS file it is a SyntaxError, so wrapping the code in async function main() { ... } and calling main() works everywhere.
The most important performance fact is that awaits in sequence add their waiting times together. When a step needs the previous result, sequential is correct. For independent work, start everything first and wait for it together with Promise.all, so the total time is roughly that of the slowest job.
Errors travel up to the caller as Promise rejections. If an async function has no try/catch, the try/catch of whichever function awaits it can catch the error, but something at the very top, such as main().catch(handleError), must handle it in the end. Otherwise it becomes an unhandled rejection.
| Pattern | Behaviour |
|---|---|
| for (const x of xs) await work(x) | one at a time; times add up |
| await Promise.all(xs.map(work)) | all at once; rejects on the first error |
| xs.forEach(async (x) => await work(x)) | nobody waits; errors escape |
- Call async fn, get a Promise at once
- At await, this function pauses
- The engine keeps running other code
- Fulfil gives a value; reject throws
Every await says 'wait here'. Always ask whether you really need to wait, or whether the jobs could start together.
General pattern
async function name(params) {
try {
const a = await stepOne(params); // dependent steps: in order
const [b, c] = await Promise.all([jobB(a), jobC(a)]); // independent
return combine(b, c); // fulfils the returned Promise
} catch (error) {
// any rejected await above lands here
} finally {
// cleanup that must always run
}
}Inside an async function, await dependent steps one by one and await independent jobs together with Promise.all. try/catch receives any rejection, and finally always runs.
Worked example: what await pauses, and what it does not
asyncCall waits for a two-second timer and then returns a string, and the script logs one more line at the end. Watch the output order: the script's last line prints before the timer finishes, because await paused only asyncCall.
function resolveAfter2Seconds() {
return new Promise((resolve) => {
setTimeout(() => resolve("resolved"), 2000);
});
}
async function asyncCall() {
console.log("calling");
const result = await resolveAfter2Seconds(); // pauses asyncCall only
console.log(result);
return "asyncCall finished";
}
asyncCall().then((message) => console.log(message));
console.log("the rest of the script keeps running");Code breakdown
- A Promise-returning helper
setTimeout(() => resolve("resolved"), 2000);resolveAfter2Seconds returns a Promise immediately and fulfils it with "resolved" two seconds later. It stands in for something like a network request.
- Pause this function
const result = await resolveAfter2Seconds(); // pauses asyncCall onlyasyncCall pauses here and hands a pending Promise back to its caller. Two seconds later result holds "resolved" and execution continues on the next line.
- Return fulfils the Promise
return "asyncCall finished";return inside an async function fulfils the Promise that asyncCall() handed out earlier with this string.
- The caller keeps going
console.log("the rest of the script keeps running");As soon as asyncCall() pauses at its await, this line runs, which is why it is the second line of output.
calling
the rest of the script keeps running
resolved
asyncCall finishedErrors and cleanup with try/catch/finally
Awaiting a rejected Promise throws at that line, so the try/catch/finally you know from synchronous code works unchanged. The show function below prints the user for a valid id and the error for an invalid one, and in both cases finally turns the spinner off.
const wait = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function loadUserOrThrow(id) {
if (id <= 0) throw new Error(`invalid id ${id}`); // becomes a rejection
return wait(10, { id, name: `user-${id}` });
}
async function show(id) {
console.log(`loading ${id}...`);
try {
const user = await loadUserOrThrow(id);
console.log("loaded", user.name);
} catch (error) {
console.log("failed:", error.message);
} finally {
console.log(`spinner off for ${id}`);
}
}
async function main() {
await show(3); // loading 3... / loaded user-3 / spinner off for 3
await show(-1); // loading -1... / failed: invalid id -1 / spinner off for -1
}
main();A throw also becomes a rejection
Because loadUserOrThrow is async, its throw does not reach the caller as a synchronous exception but as a rejected Promise. show awaits it, which is why its catch block receives the error. main awaits each show call, so the three lines for 3 finish before the lines for -1 begin.
In real projects
Async/await in real projects
Most modern JavaScript, from Express and Fastify route handlers to React data loaders and CLI scripts, is written with async/await. The same patterns keep coming back: dependent steps in order, independent requests in parallel, and cleanup in finally.
- A product page starts the product, reviews and stock requests together and waits with await Promise.all. Three 300 ms requests take roughly 900 ms one after another but roughly 300 ms in parallel.
- A checkout flow must create the order, then charge the card, then send the email, so awaiting each step in turn is correct: every step needs the previous result.
- A data import script processes thousands of rows in batches with for...of and await, so it never floods the database with too many requests at once.
Common mistakes
Common mistakes with async/await
Using an async callback inside forEach
forEach ignores the Promise each callback returns, so the work is not finished when the loop ends and errors escape your try/catch. Use for...of for sequential work and Promise.all(items.map(...)) for parallel work.
Awaiting independent work one by one
In const a = await getA(); const b = await getB(); the second call waits for no reason if getB does not need a. Write const [a, b] = await Promise.all([getA(), getB()]) instead.
Forgetting await
Writing const user = getUser(id); without await leaves user holding a Promise, so user.name is undefined, and a rejection is not caught by your try/catch. Every time you call a Promise-returning function, decide whether to await it or return it.
Best practices
Best practices
- Before writing await, ask whether this step really needs the previous result; if not, start the jobs together.
- Put try/catch where you can actually handle the error, by showing a message or using a fallback, instead of wrapping every single await.
- Keep cleanup such as clearing a loading flag or releasing a lock in finally, which runs even if the catch block returns.
- End a script's entry point with main().catch(...) so no rejection is ever left unhandled.
Mini challenge
Mini challenge: sequential and parallel loaders
Write two ways to load a list of users with a fake fetchUser. Track the peak number of requests in flight and show that it is 1 for the sequential loader and 3 for the parallel one. Keep ui.loading correct with finally, whether the load succeeds or fails.
- fetchUser throws for an unknown id and updates the active/peak counters
- loadSequential uses for...of with await (no forEach)
- loadParallel uses Promise.all with map
- run uses try/catch/finally so ui.loading always ends up false
const delays = { 1: 30, 2: 10, 3: 20 }; // fake response time per user id
let active = 0; // requests in flight right now
let peak = 0; // the most requests that were ever in flight together
async function fetchUser(id) {
// TODO: throw new Error(`user ${id} not found`) when id is not in delays
// TODO: active += 1, update peak, wait delays[id] ms, active -= 1
// TODO: return { id, name: `user-${id}` }
}
async function loadSequential(ids) {
// TODO: for...of + await, collect users in order
}
function loadParallel(ids) {
// TODO: start every request at once and wait for all of them
}
const ui = { loading: false };
async function run(label, loader, ids) {
// TODO: set ui.loading, reset peak, try/catch/finally, print names and peak
}
// TODO: in an async main(), run sequential [1, 2, 3], parallel [1, 2, 3],
// and parallel [2, 9] (the last one should report an error)Expected: sequential: user-1, user-2, user-3 (peak 1), then parallel: user-1, user-2, user-3 (peak 3), then parallel: error: user 9 not found, each followed by a "loading is now false" line.
Show hint
Await a timer with await new Promise((resolve) => setTimeout(resolve, ms)). Await each run call inside main() so the output lines do not interleave.
Show solution
const delays = { 1: 30, 2: 10, 3: 20 }; // fake response time per user id
let active = 0; // requests in flight right now
let peak = 0; // the most requests that were ever in flight together
async function fetchUser(id) {
if (!(id in delays)) throw new Error(`user ${id} not found`);
active += 1;
peak = Math.max(peak, active);
await new Promise((resolve) => setTimeout(resolve, delays[id]));
active -= 1;
return { id, name: `user-${id}` };
}
async function loadSequential(ids) {
const users = [];
for (const id of ids) {
users.push(await fetchUser(id)); // waits for each one before the next
}
return users;
}
function loadParallel(ids) {
return Promise.all(ids.map((id) => fetchUser(id))); // all start at once
}
const ui = { loading: false };
async function run(label, loader, ids) {
ui.loading = true;
peak = 0;
try {
const users = await loader(ids);
console.log(label, users.map((u) => u.name).join(", "), `(peak ${peak})`);
} catch (error) {
console.log(label, "error:", error.message);
} finally {
ui.loading = false;
}
console.log(label, "loading is now", ui.loading);
}
async function main() {
await run("sequential:", loadSequential, [1, 2, 3]);
await run("parallel:", loadParallel, [1, 2, 3]);
await run("parallel:", loadParallel, [2, 9]);
}
main();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An async function always returns a Promise: return fulfils it and throw rejects it.
- await pauses only the current async function; the engine keeps running other code.
- A rejected await throws, so try/catch/finally handles async errors and cleanup.
- Await dependent steps in order, await independent work together with Promise.all, and avoid forEach(async ...).
MDN — Asynchronous JavaScript — MDN Web Docs