Lesson 8 of 12 · 10 min · Asynchronous JavaScript

async/await and error handling

Covers: JavaScript (ECMAScript 2025) in current browsers and Node.js 22 or newer. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • Write asynchronous code that reads like synchronous code with async and await
  • Handle errors with try/catch/finally
  • Choose between sequential and parallel awaits
  • Use await correctly 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 async function always returns a promise: a returned value is wrapped in a fulfilled promise, and a thrown error becomes a rejected one.
  • await can be used inside async functions (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, await throws the error.
  • While awaiting, JavaScript is not blocked: the event loop runs other tasks. The code after await continues as a microtask.
  • Arrow functions: const load = async () => { ... }; methods: async fetchData() { ... }; class methods and object methods can be async too.

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 try block (including a rejected await) jumps to catch.
  • finally is for cleanup: hide spinners, release locks, close connections.
  • Keep try blocks 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 empty catch.
  • 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; check error instanceof Error or error.name when 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: forEach ignores returned promises. Use for...of (sequential) or Promise.all(array.map(...)) (parallel).
  • await inside .map(async ...) returns an array of promises; wrap it in Promise.all.
  • Starting thousands of requests at once can overwhelm the server or hit rate limits; limit concurrency.
  • Do not await inside 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] or undefined properties).
  • await in a non-async function (a syntax error).
  • Sequential awaits for independent calls.
  • forEach with async.
  • An empty catch that hides failures.
  • Not checking response.ok after fetch.
  • No timeout or cancellation on network calls.
  • Mixing .then chains and await in confusing ways.

Try it yourself

  1. Convert a promise chain you wrote earlier to async/await with try/catch/finally.
  2. Fetch three independent resources sequentially and then with Promise.all; compare the time.
  3. Replace a forEach(async ...) with for...of and then with Promise.all(map(...)).
  4. Write getJson that throws an HttpError, and handle 404 and 500 differently.
  5. Add retry with 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

  • async functions return promises; await pauses until a promise settles and throws on rejection.
  • Handle errors with try/catch/finally; check response.ok; use custom errors and cause.
  • Await independent work in parallel with Promise.all; avoid forEach(async ...).
  • Add timeouts, cancellation and bounded retries; handle unhandled rejections globally for reporting.

Going deeper

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.