Skip to content

Lesson 26 of 50Async JavaScript

Promises

Create, chain and combine promises, handle errors in one place, and pick the right Promise combinator.

24 min read0/8 questions

Every network request, database query and file read in modern JavaScript returns a promise. fetch, Prisma, the AWS SDK, Node's fs/promises: all of them. async/await (next lesson) is just nicer syntax on top, so when an async bug appears, like an error that vanishes or requests that run one by one when they could run together, you need to understand the promise underneath.

Before promises: callbacks

The original way to handle async work was to pass a callback that the host calls when the work is done. Node's convention put the error first: (err, result) => {}.

getUser(1, (err, user) => {
  if (err) return handle(err);
  getOrders(user.id, (err, orders) => {
    if (err) return handle(err);
    getInvoice(orders[0].id, (err, invoice) => {
      if (err) return handle(err);
      console.log(invoice.total);
    });
  });
});

Each step that depends on the previous one nests one level deeper. This shape is known as callback hell (or the pyramid of doom). Error handling is repeated at every level, it is easy to forget one, and running steps in parallel and waiting for all of them needs hand-written counters.

What a promise is

A promise is an object that stands for a value that will be available later. It is always in one of three states:

  • pending: the work is not finished yet.
  • fulfilled: it finished successfully with a value.
  • rejected: it failed with a reason (usually an Error).
Promise states
pendingfulfilledrejectedresolve(value)reject(error)

currentwaitingdone

Every promise starts pending: the request is in flight, the timer is ticking.

1/4

A promise that is fulfilled or rejected is settled, and once settled it never changes again. You react to the outcome by registering handlers:

  • .then(onFulfilled) runs with the value.
  • .catch(onRejected) runs with the error.
  • .finally(fn) runs either way, with no argument. Good for hiding a spinner or closing a connection.
JavaScript
const ok = Promise.resolve(42); // already fulfilledconst bad = Promise.reject(new Error("nope")); // already rejected ok.then((value) => console.log("value:", value));bad .catch((err) => console.log("caught:", err.message)) .finally(() => console.log("cleanup runs either way")); console.log("handlers registered; they run later as microtasks");
Output
Press Run (⌘ Enter) to see what happens.

Notice the last line prints first. Handlers always run asynchronously, as microtasks, even when the promise is already settled. That consistency is a feature: a then callback never runs in the middle of your current code.

Quick check
A promise was rejected. Later, the code that created it tries to call resolve(5). What happens?
Need a nudge? A hint rules out a wrong answer.

Creating a promise

Most of the time you consume promises that libraries give you. When you need to wrap a callback API or a timer, use the Promise constructor. It takes an executor function that receives resolve and reject:

JavaScript
function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms));} function rollDice(sides) { return new Promise((resolve, reject) => { if (sides < 1) reject(new Error("a die needs at least one side")); else resolve(Math.ceil(Math.random() * sides)); });} const started = Date.now();await sleep(100);console.log(`slept about ${Math.round((Date.now() - started) / 100) * 100} ms`); const roll = await rollDice(6);console.log(roll >= 1 && roll <= 6);await rollDice(0).catch((err) => console.log("rejected:", err.message));
Output
Press Run (⌘ Enter) to see what happens.

The executor runs immediately and synchronously when you call new Promise. Only the handlers are deferred. If the executor throws, the promise is rejected with that error. (Top-level await, used above, is covered next lesson; for now read it as "wait for this promise".)

Chaining

.then returns a new promise, resolved with whatever your handler returns. That is what lets you chain steps in a flat line instead of nesting:

  • Return a plain value: the next .then receives it.
  • Return a promise: the chain waits for it, and the next .then receives its result.
  • Throw: the chain skips to the next .catch.
JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));const getUser = (id) => sleep(10).then(() => ({ id, name: "Ada" }));const getOrders = (user) => sleep(10).then(() => [{ id: 7, total: 30 }, { id: 8, total: 12 }]); await getUser(1) .then((user) => getOrders(user)) // return a promise: the chain waits for it .then((orders) => orders.reduce((sum, o) => sum + o.total, 0)) // return a value .then((total) => console.log("total:", total)) .catch((err) => console.log("failed:", err.message)); // one catch for every step
Output
Press Run (⌘ Enter) to see what happens.

The callback-hell example becomes four flat lines with one error handler.

Predict the outputJavaScript

What does this print?

Promise.resolve(2)
.then((x) => x * 3)
.then((x) => { x + 1; })
.then((x) => console.log(x));
Need a nudge? Hints walk you through it.

Error propagation

A rejection skips every .then until it reaches a .catch. After a .catch handles it, the chain continues fulfilled with whatever the catch returned. So a .catch in the middle acts like a recovery point.

Predict the outputJavaScript

What does this print?

Promise.resolve(1)
.then(() => { throw new Error("boom"); })
.then(() => console.log("skipped?"))
.catch((e) => { console.log("caught", e.message); return "fallback"; })
.then((v) => console.log("then", v));
Need a nudge? Hints walk you through it.

Combining promises

Often you have several independent async operations. Start them all, then combine with one of four static methods. Each takes an array of promises and returns one promise.

MethodFulfils whenRejects whenUse for
Promise.allAll fulfil (array of values, in input order)Any rejects (fails fast)Load everything a page needs; all or nothing
Promise.allSettledAll settle, alwaysNeverBatch jobs where you want every result, success or failure
Promise.raceThe first to settle fulfilsThe first to settle rejectsTimeouts: race the work against a timer
Promise.anyThe first to fulfilAll reject (AggregateError)Try several mirrors, take the fastest success
JavaScript
const delay = (ms, value, fail = false) => new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms)); console.log(await Promise.all([delay(30, "a"), delay(10, "b")])); // input order, not finish order try { await Promise.all([delay(30, "a"), delay(10, "b failed", true)]);} catch (e) { console.log("all rejected:", e.message);} const settled = await Promise.allSettled([delay(10, "ok"), delay(5, "bad", true)]);console.log(settled.map((r) => r.status)); console.log(await Promise.race([delay(30, "slow"), delay(10, "fast")]));console.log(await Promise.any([delay(5, "x", true), delay(20, "first success")]));
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/4 matched

Pick the combinator for each job.

Choose an item, then its match on the other side.
Quick check
Three requests each take 1 second. How long does Promise.all([a(), b(), c()]) take?
Need a nudge? A hint rules out a wrong answer.

Unhandled rejections in depth

The warning above says Node crashes on an unhandled rejection. On a real team that line decides whether one bad request takes down a server, so it is worth knowing exactly when a rejection counts as "unhandled".

The rule: after a promise is rejected, the runtime waits until the current microtasks have finished. If by then no handler is attached to that promise, it reports an unhandled rejection. It does not matter that you plan to attach one later.

That makes this innocent-looking code crash Node, even though there is a try/catch:

const sleep = (ms, value, fail) =>
  new Promise((res, rej) => setTimeout(() => (fail ? rej(new Error(value)) : res(value)), ms));
 
const a = sleep(50, "a");               // starts now, takes 50 ms
const b = sleep(10, "b failed", true);  // starts now, fails after 10 ms
 
try {
  console.log(await a);  // still waiting here when b fails
  console.log(await b);  // too late: nobody was listening to b at 10 ms
} catch (e) {
  console.log("caught", e.message);    // never runs
}
// Node: Error: b failed ... process exits with code 1

Starting both requests early was a good idea. Awaiting them one at a time was not: while the code is stuck on await a, b rejects with no handler attached. The fix is to hand both to a combinator, which attaches handlers to every input immediately: const [x, y] = await Promise.all([a, b]). This is one of the most common causes of mysterious production crashes in Node services, and the forEach(async ...) bug from Async Patterns is a close cousin.

What each runtime does:

RuntimeOn an unhandled rejectionIf a handler is attached later
BrowsersFire unhandledrejection on window (or self in a worker), log to the console, keep runningFire rejectionhandled
Node (15+)Emit process.on("unhandledRejection"); if nothing listens, throw it as an uncaught exception and exit with code 1Emit rejectionHandled

Other server runtimes are similarly strict by default; check their docs. Node's behaviour is set by the --unhandled-rejections flag. The default is throw; strict, warn and none also exist. Do not switch production servers to warn to make crashes go away. A process that keeps running after an unknown failure may be holding a broken database connection or half-written state. The usual production setup is: log the reason to your error tracker in an unhandledRejection listener, then let the process exit and have the platform (Kubernetes, systemd, your host) restart it.

process.on("unhandledRejection", (reason) => {
  logger.fatal({ err: reason }, "unhandled rejection");
  process.exitCode = 1;
  // let in-flight work finish or time out, then exit
});
Quick check
A Node 24 server runs const u = getUser(); const o = getOrders(); const user = await u; const orders = await o; inside a try/catch. getOrders rejects quickly while getUser is slow. What happens?
Need a nudge? A hint rules out a wrong answer.

Promise.withResolvers (ES2024)

The Promise constructor hands you resolve and reject only inside the executor. Sometimes the code that creates the promise is not the code that settles it: a queue that resolves a waiting consumer when an item arrives, a test that resolves a fake request on demand, a wrapper around an event that fires later. People used to write a "deferred" helper that leaked resolve out of the executor into outer variables.

Promise.withResolvers() is that helper, built in. It returns { promise, resolve, reject }. It is in all current browsers and in Node 22 and later.

JavaScript
class AsyncQueue { #items = []; #waiting = []; push(item) { const next = this.#waiting.shift(); if (next) next.resolve(item); // a consumer is waiting: hand it over else this.#items.push(item); } pop() { if (this.#items.length > 0) return Promise.resolve(this.#items.shift()); const deferred = Promise.withResolvers(); this.#waiting.push(deferred); // settle it later, from push() return deferred.promise; }} const queue = new AsyncQueue();const consumer = (async () => { for (let i = 0; i < 3; i++) { const job = await queue.pop(); // waits until something is pushed console.log("got", job); }})(); queue.push("email-1");setTimeout(() => queue.push("email-2"), 10);setTimeout(() => queue.push("email-3"), 20);await consumer;console.log("consumer done");
Output
Press Run (⌘ Enter) to see what happens.

The same rules apply as with the constructor: settling happens once, and later calls are ignored. The danger is new, though. A promise whose resolve is stored somewhere can be forgotten, and then whoever awaits it waits forever. When you hand out resolvers, also decide what happens on timeout or shutdown: reject every waiting deferred with a clear error.

Promise.try (ES2025)

A function that "returns a promise" can still fail before it returns one, by throwing synchronously: a JSON.parse on bad input, a TypeError from a missing argument. That throw does not become a rejection. It escapes straight past your .catch.

Promise.try(fn, ...args) calls fn right away (synchronously, not on a later tick) and wraps whatever happens in a promise. A returned value fulfils it, a returned promise is followed, and a sync throw becomes a rejection. It shipped in all major browsers during late 2024 and early 2025, and is in current Node; check your targets if you support older runtimes.

JavaScript
function parseConfig(text) { return JSON.parse(text); // throws synchronously on bad input} // Without Promise.try: the sync throw escapes before any .catch is attachedtry { Promise.resolve(parseConfig("{bad")).catch(() => console.log("never reached"));} catch (e) { console.log("escaped synchronously:", e.name);} // With Promise.try: sync throws and async rejections take the same pathawait Promise.try(parseConfig, "{bad") .then((cfg) => console.log("config", cfg)) .catch((e) => console.log("caught as a rejection:", e.name)); const value = await Promise.try(() => 42);console.log("plain value:", value);
Output
Press Run (⌘ Enter) to see what happens.

Before this existed, the idiom was Promise.resolve().then(fn), which also catches sync throws but delays fn to a microtask, or new Promise((resolve) => resolve(fn())). Inside an async function you rarely need any of them, because a sync throw in an async function already becomes a rejection. Promise.try earns its place in library code and plugin systems that call functions they did not write and cannot know are async.

Microtask ordering puzzles

You saw the basic ordering in The Event Loop: synchronous code, then all microtasks, then the next task. Interviews go one level deeper, into how promise chains interleave. Three rules explain every puzzle:

  1. Each .then callback is one microtask. When it finishes, the next .then in that chain is queued at the back of the microtask queue, not run right away.
  2. Two chains therefore take turns, one step each.
  3. Returning a promise (or any thenable) from a .then callback, or from an async function, costs two extra microtask turns before the chain moves on. The engine has to call that promise's then in a job of its own and then wait for it to report back.
Two chains take turns

Call stack

  • script

Web APIs / timers

    Microtasks

    • a1
    • b1

    Task queue

      Console

      Both Promise.resolve() are already fulfilled, so the first .then of each chain is queued: a1, then b1. The rest of each chain is not queued yet.

      1/5
      JavaScript
      Promise.resolve() .then(() => console.log("a1")) .then(() => console.log("a2")) .then(() => console.log("a3"));Promise.resolve() .then(() => console.log("b1")) .then(() => console.log("b2")) .then(() => console.log("b3"));
      Output
      Press Run (⌘ Enter) to see what happens.

      Now the harder one, which tests rule 3:

      Predict the outputJavaScript

      What does this print?

      Promise.resolve()
      .then(() => { console.log("a1"); return Promise.resolve("x"); })
      .then(() => console.log("a2"));
      Promise.resolve()
      .then(() => console.log("b1"))
      .then(() => console.log("b2"))
      .then(() => console.log("b3"))
      .then(() => console.log("b4"));
      Need a nudge? Hints walk you through it.

      async functions follow the same rules. await on a native promise or a plain value costs one turn, and everything before the first await runs synchronously, as part of the caller:

      JavaScript
      async function task() { console.log("task start"); // runs synchronously, inside the call await null; console.log("task after await"); // a microtask} console.log("script start");setTimeout(() => console.log("timeout"), 0);task();Promise.resolve().then(() => console.log("then"));console.log("script end");
      Output
      Press Run (⌘ Enter) to see what happens.

      The output is script start, task start, script end, task after await, then, timeout. The await continuation was queued before the .then, so it runs first, and the timer waits for all microtasks.

      Two honest warnings. First, the exact extra-tick counts are defined by the spec and are stable across engines today, but you should never write code that depends on them. If B must happen after A, chain it or await it. Second, in an interview, narrate the queue out loud as you go ("this queues a microtask, this goes to the task queue"). The reasoning is what is being scored, and saying it lets the interviewer give credit even if you miscount one tick.

      Put it in order6 steps

      Order the output of the task() example above.

      1. Tap the steps below in the right order.
      Need a nudge? A hint shows where it starts.
      ChallengeEasy

      sleep

      Write sleep(ms) that returns a promise which resolves (with no value) after ms milliseconds. It is the building block for retries, polling and animations.

      console.log("start");
      await sleep(500);
      console.log("half a second later");
      JavaScript
      function sleep(ms) { // Wrap setTimeout in a new Promise. return Promise.resolve();}
      ChallengeMedium

      Promise.all from scratch

      Write promiseAll(items) that behaves like Promise.all, without using Promise.all, allSettled, race or any:

      • Returns a promise that resolves to an array of results in input order (not finish order).
      • Items may be promises or plain values.
      • Rejects as soon as any item rejects, with that error.
      • An empty array resolves to [].
      • All items run at the same time (they were already started when you received them).
      const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
      await promiseAll([delay(30, "a"), "b", delay(10, "c")]); // ["a", "b", "c"]
      JavaScript
      function promiseAll(items) { // Return a new Promise; store each result by index and count completions. return Promise.resolve([]);}
      Key terms
      promise
      An object representing a future value, in one of three states: pending, fulfilled or rejected.
      settled
      Fulfilled or rejected. A settled promise never changes again.
      executor
      The (resolve, reject) => {} function passed to new Promise. It runs immediately.
      chaining
      Each .then returns a new promise resolved with the handler's return value, so steps stay flat.
      unhandled rejection
      A rejected promise with no handler. Logged in browsers, crashes Node by default.
      Promise.all
      Waits for every promise; resolves with all values in input order, rejects on the first failure.
      Promise.withResolvers
      ES2024. Returns { promise, resolve, reject } so code outside an executor can settle the promise.
      Promise.try
      ES2025. Calls a function now and wraps its result, returned promise or sync throw in a promise.
      microtask
      A small job run as soon as the call stack is empty, before the next task. Promise callbacks are microtasks.