Lesson 8 of 12 · 10 min · Asynchronous JavaScript
async/await and error handling
What you will learn
- Write asynchronous code that reads like synchronous code with
asyncandawait - Handle errors with
try/catch/finally - Choose between sequential and parallel awaits
- Use
awaitcorrectly in loops and with array methods - Build custom errors, retries and timeouts
In simple words
async and await are a nicer way to use promises. You mark a function async, and inside it you write await in front of anything that takes time. The function pauses at that line, the rest of the page keeps running, and when the result arrives the function continues, as if the line had simply taken a while. Errors are handled with the ordinary try/catch, so the code reads top to bottom.
Words to know
- async function: a function that always returns a promise and can use
await. - await: pause the async function until a promise settles, then continue with its value.
- try/catch: the block that handles errors thrown inside it.
- Retry: trying an operation again after it fails.
async and await
async function loadOrders() {
const response = await fetch("/api/orders"); // pauses here, without blocking the page
const orders = await response.json();
return orders.filter((o) => o.status === "paid");
}
const paid = await loadOrders(); // or: loadOrders().then(...)
Rules:
- An
asyncfunction always returns a promise: a returned value is wrapped in a fulfilled promise, and a thrown error becomes a rejected one. awaitcan be used insideasyncfunctions (and at the top level of ES modules). It takes a promise (or any value), waits, and gives you the fulfilled value; if the promise rejects,awaitthrows the error.- While awaiting, JavaScript is not blocked: the event loop runs other tasks. The code after
awaitcontinues as a microtask. - Arrow functions:
const load = async () => { ... }; methods:async fetchData() { ... }; class methods and object methods can beasynctoo.
try, catch and finally
async function loadDashboard() {
showSpinner();
try {
const response = await fetch("/api/dashboard");
if (!response.ok) {
throw new Error(`Server returned ${response.status}`); // fetch does not reject on HTTP errors (next lesson)
}
const data = await response.json();
render(data);
} catch (error) {
console.error("Could not load the dashboard", error);
showMessage("Something went wrong. Please try again.");
} finally {
hideSpinner(); // runs on success and on failure
}
}
- Anything that throws or rejects in the
tryblock (including a rejectedawait) jumps tocatch. finallyis for cleanup: hide spinners, release locks, close connections.- Keep
tryblocks small and purposeful, and catch where you can do something useful: show a message, retry or fall back. Do not swallow errors silently with an emptycatch. - If you do not catch, the rejection propagates to whoever awaits your function. At the top of an event handler, someone must handle it.
catch (error): errors can be anything that was thrown; checkerror instanceof Errororerror.namewhen needed.
You can mix styles: const data = await fetchData().catch(() => null); handles one call's failure inline.
Sequential versus parallel
await one after another waits for each:
// Sequential: total time = a + b + c
const user = await getUser();
const orders = await getOrders();
const offers = await getOffers();
If the calls do not depend on each other, start them together and await them together:
// Parallel: total time = the slowest
const [user, orders, offers] = await Promise.all([getUser(), getOrders(), getOffers()]);
// Or start first, await later:
const ordersPromise = getOrders();
const user = await getUser();
const orders = await ordersPromise;
Use sequential awaits only when a step needs the previous result (getOrders(user.id)). Be careful with a failing parallel call: Promise.all rejects on the first error; use Promise.allSettled for best-effort loading. If you start a promise and await something that throws first, the unawaited promise may reject unhandled.
await in loops and array methods
// Sequential, one at a time (order matters, or avoid overloading the server):
for (const id of ids) {
const result = await processOrder(id);
results.push(result);
}
// Parallel, all at once:
const results = await Promise.all(ids.map((id) => processOrder(id)));
// A concurrency limit (say 5 at a time): use a small pool library such as p-limit, or process in chunks.
Traps:
array.forEach(async (id) => { await ... })does not wait:forEachignores returned promises. Usefor...of(sequential) orPromise.all(array.map(...))(parallel).awaitinside.map(async ...)returns an array of promises; wrap it inPromise.all.- Starting thousands of requests at once can overwhelm the server or hit rate limits; limit concurrency.
- Do not
awaitinside a tight loop if the calls are independent.
Error handling patterns
Custom error classes make errors easy to recognise:
class HttpError extends Error {
constructor(status, message) {
super(message);
this.name = "HttpError";
this.status = status;
}
}
async function getJson(url) {
const response = await fetch(url);
if (!response.ok) throw new HttpError(response.status, `Request to ${url} failed`);
return response.json();
}
try {
await getJson("/api/orders/5");
} catch (error) {
if (error instanceof HttpError && error.status === 404) showNotFound();
else if (error instanceof HttpError && error.status >= 500) showServerProblem();
else throw error; // not ours: rethrow
}
Pass the original error along with new Error("could not save order", { cause: error }) (ES2022) to keep the chain for debugging.
Retries with delay and backoff for temporary failures (network drops, 503s):
async function retry(task, { attempts = 3, delayMs = 500 } = {}) {
for (let attempt = 1; ; attempt++) {
try {
return await task();
} catch (error) {
if (attempt >= attempts) throw error;
await new Promise((r) => setTimeout(r, delayMs * 2 ** (attempt - 1))); // 500, 1000, 2000 ms
}
}
}
const orders = await retry(() => getJson("/api/orders"));
Retry only safe, idempotent operations (GET), and not errors that will never succeed (400, 401, 404). Add jitter (random delay) in real systems.
Timeouts and cancellation use an AbortController (also AbortSignal.timeout(ms)), which cancels the actual request instead of just ignoring it:
const response = await fetch(url, { signal: AbortSignal.timeout(5000) }); // aborts after 5 s with a TimeoutError
Global safety nets for errors nobody handled:
window.addEventListener("unhandledrejection", (event) => { report(event.reason); });
window.addEventListener("error", (event) => { report(event.error); });
// Node.js:
process.on("unhandledRejection", (reason) => { console.error(reason); process.exit(1); });
Use them for logging and reporting (Sentry and similar tools), not for regular error handling.
Top-level await
In ES modules (browser type="module" and Node.js ESM) you can await outside a function:
const config = await fetch("/config.json").then((r) => r.json());
The module (and modules that import it) waits for it, so use it for essential start-up data, not for slow optional work.
Async iteration
for await...of loops over async sources (streams, paginated APIs):
async function* pages(url) {
let next = url;
while (next) {
const data = await getJson(next);
yield data.items;
next = data.nextUrl;
}
}
for await (const items of pages("/api/orders?page=1")) { render(items); }
Common mistakes
- Forgetting
await, getting a promise instead of the value ([object Promise]orundefinedproperties). awaitin a non-async function (a syntax error).- Sequential awaits for independent calls.
forEachwithasync.- An empty
catchthat hides failures. - Not checking
response.okafterfetch. - No timeout or cancellation on network calls.
- Mixing
.thenchains andawaitin confusing ways.
Try it yourself
- Convert a promise chain you wrote earlier to
async/awaitwithtry/catch/finally. - Fetch three independent resources sequentially and then with
Promise.all; compare the time. - Replace a
forEach(async ...)withfor...ofand then withPromise.all(map(...)). - Write
getJsonthat throws anHttpError, and handle 404 and 500 differently. - Add
retrywith exponential backoff and a 5-second timeout to a flaky call.
Check yourself
What does an async function return?
A promise: fulfilled with the returned value, or rejected with an error thrown inside it.
What happens when you await a rejected promise?
The await expression throws the rejection reason, which can be caught with try/catch.
Why does array.forEach(async ...) not wait for its callbacks?
forEach ignores the promises its callback returns; use for...of with await, or await Promise.all(array.map(...)).
How do you run three independent async calls in parallel with await?
Start them together and await Promise.all([a(), b(), c()]).
Interview questions
How is async/await related to promises?
It is syntax over promises: an async function returns a promise and await pauses until a promise settles, using promise handlers (microtasks) underneath, with errors handled by try/catch.
How would you handle errors from several awaited calls?
Wrap them in try/catch (with finally for cleanup), use Promise.allSettled when failures should not stop the others, check response.ok, and map known error types to user messages.
How do you add a timeout to an async operation?
Pass AbortSignal.timeout(ms) as the signal to fetch (which cancels the request), or use Promise.race with a timeout promise for operations that cannot be aborted.
Summary
asyncfunctions return promises;awaitpauses until a promise settles and throws on rejection.- Handle errors with
try/catch/finally; checkresponse.ok; use custom errors andcause. - Await independent work in parallel with
Promise.all; avoidforEach(async ...). - Add timeouts, cancellation and bounded retries; handle unhandled rejections globally for reporting.
Going deeper
- MDN: async function: syntax and behaviour.
- MDN: await: including top-level await.
- MDN: Error handling:
try,catch,throwand custom errors. - MDN: AbortSignal.timeout(): timeouts and cancellation.
See how much of this you can explain
A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.