Skip to content
FrontDepth, Home

JavaScript Deep Dive

Promises and async/await

How JavaScript represents results that arrive later: promise states and chains, async/await and its microtasks, error handling, parallel work and combinators, cancellation with AbortController, and latest-only requests in UI.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

This topic starts at Junior level.

JuniorConcept

What a promise is

A is an object that stands for a result that is not ready yet: a network response, a timer, a file read. Instead of taking a , an asynchronous function returns a promise immediately, and you attach reactions to it.

Three states

  • pending: the work has not finished;
  • fulfilled: it finished with a value;
  • rejected: it failed with a reason, usually an Error.

Fulfilled and rejected together are called settled. A promise settles at most once. After that its state and value never change, and later calls to resolve or reject are ignored.

JavaScript
function delay(ms, value) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), ms);
  });
}

delay(500, "ready").then((value) => console.log(value)); // "ready" after 500 ms

The function passed to new Promise is the executor. It runs synchronously, inside the constructor, and receives two functions: resolve and reject. If the executor throws, the promise is rejected with that error.

Reactions always run later

A then callback never runs synchronously, even when the promise is already settled. It is queued as a and runs after the current synchronous code has finished:

JavaScript
const done = Promise.resolve(42);
done.then((value) => console.log("then " + value));
console.log("sync");
// sync
// then 42

This "always asynchronous" rule removes a whole class of bugs where a callback sometimes runs immediately and sometimes later, depending on whether the data was cached.

When you write new Promise

Rarely. fetch, response.json(), async functions and most modern APIs already return promises. new Promise is for wrapping an API that only offers callbacks or events, as delay wraps setTimeout above.

JuniorConcept

Chaining: then, catch and finally

Every call to then returns a new promise. What its callback does decides how that new promise settles:

  • returns a value → the new promise is fulfilled with that value;
  • returns a promise → the new promise follows it, so the chain waits;
  • throws → the new promise is rejected with the error.
JavaScript
fetch("/api/user")
  .then((response) => {
    if (!response.ok) throw new Error("HTTP " + response.status);
    return response.json();
  })
  .then((user) => fetch("/api/teams/" + user.teamId))
  .then((response) => response.json())
  .then((team) => renderTeam(team))
  .catch((error) => showError(error.message))
  .finally(() => hideSpinner());

How errors travel

A rejection skips every success handler until it reaches a catch (or the second argument of a then). catch(fn) is just then(undefined, fn). If the handler returns normally, the chain is recovered: the next then receives the returned value. To keep the chain rejected, rethrow.

JavaScript
Promise.reject(new Error("offline"))
  .then(() => console.log("not called"))
  .catch((error) => {
    console.log("caught: " + error.message);
    return [];
  })
  .then((items) => console.log("items: " + items.length));
// caught: offline
// items: 0

finally

finally(fn) runs on both outcomes, receives no argument and passes the original value or error through unchanged. The exception: if fn throws or returns a rejected promise, that new error replaces the result. Use it for cleanup, such as hiding a spinner or releasing a lock.

Common mistakes

  • Forgetting return inside then: the next step receives undefined and does not wait for the inner promise.
  • Nesting then inside then instead of returning the promise and continuing the chain.
  • Expecting fetch to reject on 404 or 500. It rejects only on network failures; check response.ok yourself, as above.
JuniorConcept

async/await: syntax over promises

is syntax on top of promises, not a separate mechanism:

  • an async function always returns a promise: return value fulfils it, throw rejects it;
  • await expression waits for the promise to settle, then evaluates to its value or throws its reason.
JavaScript
async function loadTeamName(userId) {
  const userResponse = await fetch("/api/users/" + userId);
  if (!userResponse.ok) throw new Error("HTTP " + userResponse.status);
  const user = await userResponse.json();

  const teamResponse = await fetch("/api/teams/" + user.teamId);
  const team = await teamResponse.json();
  return team.name;
}

loadTeamName(7).then((name) => console.log(name));

The code reads top to bottom, but it is still the same chain of promises as in the previous section.

What await does to the rest of the function

The code before the first await runs synchronously, as part of the call. At await the function is suspended: control returns to the caller, which gets a pending promise. When the awaited promise settles, the rest of the function is scheduled as a microtask. This happens even when the value is already available: await null still pauses until the current synchronous code, and the microtasks queued before it, have run.

JavaScript
async function task() {
  console.log("2: inside, before await");
  await null;
  console.log("4: after await");
}

console.log("1: before the call");
task();
console.log("3: after the call");

Only the async function itself pauses. The rest of the program keeps running, which is why the caller's next line logs before "4".

Errors with try/catch

A rejected await throws at that line, so ordinary try/catch/finally works:

JavaScript
async function save(draft) {
  setSaving(true);
  try {
    await api.saveDraft(draft);
  } catch (error) {
    showToast(error.message);
  } finally {
    setSaving(false);
  }
}

await is allowed only inside async functions and at the top level of ES modules.

MiddlePitfalls

Error handling and unhandled rejections

A catch has to see the promise

try/catch catches a rejection only if the promise is awaited inside the try:

JavaScript
async function getUser(id) {
  try {
    return fetchUser(id);
  } catch (error) {
    return null;
  }
}

return fetchUser(id) hands the promise out without waiting. The function leaves the try block at once, and when the promise rejects later, the catch never runs: the caller gets the rejection. return await fetchUser(id) fixes it. Outside a try, return await changes nothing you would notice.

Fire-and-forget calls

Calling an async function without await, return or .catch() throws its errors away:

JavaScript
button.addEventListener("click", () => {
  saveDraft();
});

If saveDraft rejects, nothing handles it. Attach .catch() where you start the work, or make the handler async and use try/catch inside.

Unhandled rejections

When a promise is rejected and has no handler after the current microtasks have run, browsers fire an unhandledrejection event on window, and DevTools logs "Uncaught (in promise)". In Node.js the default mode --unhandled-rejections=throw (since v15) turns it into an uncaught exception, which ends the process unless a process.on("unhandledRejection") handler exists.

JavaScript
window.addEventListener("unhandledrejection", (event) => {
  monitoring.capture(event.reason);
});

Use such a global handler for reporting, not for control flow.

forEach does not wait

JavaScript
async function saveAll(items) {
  items.forEach(async (item) => {
    await save(item);
  });
  console.log("all saved");
}

forEach ignores the promises its callback returns, so "all saved" is logged before any save finishes and failed saves become unhandled rejections. Use for...of with await to run them one by one, or await Promise.all(items.map(save)) to run them in parallel.

Smaller rules

  • Reject with Error objects. reject("failed") has no stack trace.
  • A catch can receive any value. Check error instanceof Error before reading error.message (in TypeScript the parameter is unknown).
  • .catch(() => {}) hides bugs. Catch where you can do something useful: show a message, retry, fall back. Let everything else propagate.
MiddleConcept

Sequential vs parallel work and the Promise combinators

Each await waits before the next line runs, so two awaits in a row are sequential: the total time is the sum of both requests.

JavaScript
const user = await getUser(id);
const orders = await getOrders(id);

If getOrders does not need user, start both and wait for both:

JavaScript
const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);

Now the total is about the slower of the two. The work starts when getUser(id) and getOrders(id) are called; Promise.all starts nothing, it only waits. Calling both first and awaiting later (const a = getUser(id); const b = getOrders(id);) runs them in parallel too, but if b rejects while you are still awaiting a, nothing handles that rejection yet: the browser reports an unhandled rejection, and Node.js ends the process. Promise.all attaches handlers to every input at once.

The four combinators

MethodFulfilsRejectsTypical use
Promise.allwhen all fulfil: values in input orderat the first rejectionevery result is required
Promise.allSettledwhen all settle: { status, value } or { status, reason } per inputneverindependent tasks, report each outcome
Promise.raceif the first input to settle fulfilsif the first input to settle rejectsfirst response, simple timeouts
Promise.anyat the first fulfilmentwhen all reject: AggregateError with an errors arrayredundant sources, fallbacks

Details that come up in reviews

  • Promise.all fails fast but cancels nothing. The other requests keep running and their results are dropped. To stop them, pass an AbortSignal (next section).
  • A Promise.race timeout only stops the waiting, not the request. For fetch, AbortSignal.timeout(ms) really ends it.
  • Empty input: Promise.all([]) fulfils with [], Promise.any([]) rejects with an AggregateError, and Promise.race([]) stays pending forever.
  • Promise.all(items.map(upload)) over 500 items starts 500 requests at once. Limit concurrency, for example with batches:
JavaScript
async function inBatches(items, size, worker) {
  const results = [];
  for (let i = 0; i < items.length; i += size) {
    const batch = items.slice(i, i + size);
    results.push(...(await Promise.all(batch.map(worker))));
  }
  return results;
}
MiddleWeb platform

Cancellation with AbortController and fetch

A promise has no cancel() method: once created, it settles on its own. What you can cancel is the work behind it. The web platform's tool for that is AbortController: it has an abort() method and a signal that you pass to APIs that support it, such as fetch, addEventListener and many Node.js APIs.

JavaScript
const controller = new AbortController();

fetch("/api/report", { signal: controller.signal })
  .then((response) => response.json())
  .then(showReport)
  .catch((error) => {
    if (error.name === "AbortError") return;
    showError(error);
  });

cancelButton.addEventListener("click", () => controller.abort());

After abort(), the fetch promise rejects with an AbortError DOMException, or with the reason you passed to abort(reason). A cancellation is not a failure to show the user, so filter it out in catch. A controller aborts only once and cannot be reset: create a new one for every operation.

Timeouts and combined signals

  • AbortSignal.timeout(ms) returns a signal that aborts by itself with a TimeoutError (Baseline widely available; in all major browsers since April 2024).
  • AbortSignal.any([a, b]) aborts as soon as any of its signals aborts, with that signal's reason (in all major browsers since March 2024).
JavaScript
async function getJSON(url, signal) {
  const signals = [AbortSignal.timeout(8000)];
  if (signal) signals.push(signal);

  const response = await fetch(url, { signal: AbortSignal.any(signals) });
  if (!response.ok) throw new Error("HTTP " + response.status);
  return response.json();
}

Making your own functions abortable

Accept a signal, give up early if it is already aborted, and listen for its abort event:

JavaScript
function delay(ms, signal) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);
    const id = setTimeout(resolve, ms);
    signal?.addEventListener(
      "abort",
      () => {
        clearTimeout(id);
        reject(signal.reason);
      },
      { once: true },
    );
  });
}

Aborting stops the client side only. A POST that already reached the server may still be processed, so writes need server-side protection (idempotency keys, version checks), not just abort().

SeniorFramework

Race conditions in UI: only the latest request wins

A search box sends a request on every change: r, re, rea, reac, react. The network does not keep the order. If the request for rea is slow and its response arrives last, the list shows results for rea while the input says react. Debouncing alone does not fix it: it sends fewer requests, but a slow response can still overtake a newer one. The platform's search-race incident lets you debug this in a running app.

The rule: apply a response only if it belongs to the latest request.

1. Ignore stale responses

react.dev recommends a cleanup flag in the effect:

JSX
useEffect(() => {
  let ignore = false;
  searchProducts(query).then((items) => {
    if (!ignore) setResults(items);
  });
  return () => {
    ignore = true;
  };
}, [query]);

When query changes, React runs the cleanup of the previous effect, so the older response is dropped even if it arrives last.

2. Abort the previous request

The same shape with AbortController also saves bandwidth and server work:

JSX
useEffect(() => {
  const controller = new AbortController();
  searchProducts(query, { signal: controller.signal })
    .then(setResults)
    .catch((error) => {
      if (error.name !== "AbortError") setError(error);
    });
  return () => controller.abort();
}, [query]);

3. Let a query library own it

TanStack Query stores each result under its queryKey. The platform's tour "TanStack Query: the life of useQuery" (v5.107.1) follows this path through QueryObserver and Query.

JSX
const { data, isPending, error } = useQuery({
  queryKey: ["search", query],
  queryFn: ({ signal }) => searchProducts(query, { signal }),
  enabled: query.length > 1,
});

Every term is a separate query, and the component reads the entry for its current key, so a late rea response lands in the rea entry and never replaces the react results. Because queryFn passes on the signal, the request is aborted when the query becomes out-of-date or inactive. Without the signal, it runs to the end and its data is cached.

Outside React

JavaScript
function latestOnly(request) {
  let controller = null;
  return (...args) => {
    controller?.abort();
    controller = new AbortController();
    return request(controller.signal, ...args);
  };
}

The same race appears in route loaders, autosave and pagination: wherever an older async result can arrive after a newer one.

SeniorWeb platform

Under the hood: microtask order, thenables, withResolvers

Counting microtask hops

Each reaction is one microtask. Resolving a promise with another promise (returning a promise from then, return somePromise in an async function, resolve(somePromise)) costs two extra hops: the spec first queues a job that calls the inner promise's then, and only that reaction settles the outer promise. await on a native promise uses it directly, in one hop.

JavaScript
async function direct() {
  return "direct";
}
async function wrapped() {
  return Promise.resolve("wrapped");
}

wrapped().then((value) => console.log(value));
direct().then((value) => console.log(value));
Promise.resolve()
  .then(() => console.log("tick 1"))
  .then(() => console.log("tick 2"));
// direct, tick 1, tick 2, wrapped

Interviewers like such puzzles, but production code must never depend on how many ticks separate two independent chains. If B needs A, chain or await it.

Thenables

await, Promise.resolve() and a value returned from then all accept any object with a then method (a thenable) and call that method in a microtask. That is how promises from different libraries work together. The flip side: any object with a then method is treated as a promise. Returning such an object from an async function calls its then, so do not give a non-promise object a method named then.

JavaScript
const task = {
  then(resolve) {
    resolve("done");
  },
};

console.log(await task); // "done"

await in loops

for (const id of ids) await load(id) is sequential by design. That is right when each step needs the previous result or the server must not get a burst of requests, and wrong when the steps are independent. ESLint's no-await-in-loop rule makes you decide explicitly. for await...of consumes async iterables, such as async generators.

Promise.withResolvers

Promise.withResolvers() returns { promise, resolve, reject }, for when the code that settles the promise lives outside an executor: events, queues, tests. It is available across browsers since March 2024 (Chrome 119, Firefox 121, Safari 17.4) and in Node.js 22.

JavaScript
function nextMessage(socket) {
  const { promise, resolve, reject } = Promise.withResolvers();
  const controller = new AbortController();
  const options = { signal: controller.signal };
  socket.addEventListener("message", (event) => resolve(event.data), options);
  socket.addEventListener("error", () => reject(new Error("socket error")), options);
  return promise.finally(() => controller.abort());
}

Promise.try(fn) (Baseline 2025) is its newer sibling: it calls fn synchronously and turns a return value, a thrown error or a returned promise into one promise.

SeniorInterview tips

Interview tips

A 30-second answer. "A promise represents a result that arrives later. It is pending, then fulfilled with a value or rejected with a reason, exactly once. then returns a new promise, so values and errors flow down the chain. async/await is syntax over the same mechanism: await suspends the function and resumes it as a microtask when the promise settles."

Questions you are likely to get

  • What does this code log? Mixed sync code, then callbacks, await and setTimeout. Walk through it: synchronous code first, then microtasks in queue order, then tasks. Mention that an executor runs synchronously.
  • What is the difference between Promise.all, allSettled, race and any? Say when each fulfils and rejects, and pick one for a concrete case: a dashboard of independent widgets is allSettled, a page that needs user and permissions is all.
  • Why are these requests slow? Sequential awaits of independent work. Show the Promise.all version and mention concurrency limits.
  • How do you cancel a request? AbortController and signal, filtering AbortError, and the fact that a promise itself cannot be cancelled.
  • Results of an old search show up. Out-of-order responses. Fix with a stale-response flag, abort() or a query library keyed by the query. Explain why a debounce alone is not enough.

Mistakes that cost points

  • Saying await blocks the thread. It suspends only the async function; the event loop keeps running.
  • Saying Promise.all runs promises in parallel. The work was already started when the promises were created; all only waits.
  • Saying async makes code run in a background thread. Promise work still runs on the main thread; CPU-heavy work needs a Web Worker.
  • try { return promise } catch {} and forEach(async ...): both lose errors.

Senior signal

Talk about design, not syntax: who owns cancellation, how a component guarantees latest-only results, how a failed request is retried without duplicating a write, and where unhandled rejections are reported in production.

JuniorReview checklist

What to check when reviewing promises and async/await

Use this list when you review code you did not write: a teammate's pull request, a snippet from a library's issue tracker or a suggestion from an AI assistant. Skip it and you let through errors that vanish without a trace, requests that wait for each other for no reason and old responses that overwrite new ones.

  • Is every promise awaited, returned or given a .catch()? A bare save(); in a click handler, items.forEach(async ...) or try { return fetchUser(id) } loses errors: no catch sees the rejection. Expect return await inside try, and for...of or Promise.all instead of forEach.
  • Does fetch code check response.ok? fetch rejects only on network failures, so a 404 or 500 goes down the success path.
  • Does every then callback return its promise? Without return, the next step gets undefined and does not wait for the inner promise.
  • Can the response to an older request be applied after a newer one? The network does not keep the order. When an effect fetches on every prop change, look for an ignore flag or an AbortController aborted in the cleanup.
  • Are independent requests awaited one after another? Two awaits in a row add up their times. Expect Promise.all, with a concurrency limit when there are hundreds of items.
  • Is cancellation handled as cancellation? catch should filter out AbortError instead of showing it, and every operation needs a new controller. A Promise.race timeout stops only the waiting; AbortSignal.timeout(ms) really ends the request.
  • Are errors silently swallowed? .catch(() => {}) hides bugs, and reject("failed") has no stack trace. Catch only where the code can show a message, retry or fall back.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 3 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.

Build Your Own X

System Design

Weekly Challenges

Frontend History

Guided tours through the source of real libraries that rely on it.