Loading

T5 Modern JavaScript (ES6 and later) · Lesson 7

Promises

Code that finishes later: why JavaScript does not stop to wait, setTimeout and the order in which waiting code runs, promises and their three states, then chains that pass values along, catching failures at one place, running many promises together with all, allSettled, race and any, and the event loop that decides what runs next.

  • say why JavaScript does not stop to wait, and use setTimeout to run code later
  • make a promise with new Promise, and say what pending, fulfilled and rejected mean
  • chain then calls that pass values and promises along, and use finally
  • handle a failure anywhere in a chain with one catch, and read an unhandled rejection
  • wait for many promises with Promise.all, allSettled, race and any
  • predict the order of synchronous code, promise callbacks and timers
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06); Google Chrome on the laptop (the kit renders every HTML block in it, and the DevTools step describes its panels) 155 (2026-11-06)Play this lesson's games

The back cover

Some work takes time: a reply from a server, a file read from the disk, a timer counting down. JavaScript does not stop and wait for it. It starts the work, carries on, and is told when the result is ready.

These pages show code that runs later, and the promise, an object that stands for a result not yet ready. They show chains of then that pass values along, and failures caught in one place. They show many promises waited for together, and the event loop, which decides what runs next.

Before you start

The story: Every clock stopped for a parcel

The upper floor orders its spare springs from a workshop across the city. When the old script sends for them, it stands at the door and waits, doing nothing else, until the courier knocks. While it waits, every clock on the floor stops. Yesterday the courier took an hour, and the whole tower lost an hour.

A newer script did not wait at all: it reached for the springs the moment it sent for them, found an empty box, and fitted nothing.

Master Hakim Verge holds up the courier's last receipt. "Waiting is not the same as stopping," he says. "Take a slip from the courier: a promise that the springs will come, or a note saying why not. Then go on with your work, and fit the springs when they arrive."

Some work cannot finish at once. A file comes from a server, a timer has to run out, a person has to press a button. JavaScript never stops to wait for such things, because while it waited, the whole page would freeze. Instead it starts the work, carries on, and deals with the result when it arrives. A promise is the object that stands for such a result before it exists.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Callbacks.button.addEventListener("click", f)Functions run later, when something happens.
Functions that take functions.list.map(fn)then and catch take functions.
Arrow functions.(v) => v * 2Short callbacks in every chain.
throw and catch.throw new RangeError(...)Failures inside promises.
Error objects.err.messageWhat a rejected promise carries.
Rethrowing.if (!(err instanceof X)) throw err;Passing failures on in a chain.
Closures.A function that remembers a value.Callbacks that remember what to do.
One thing at a time.The Console prints lines in order.What runs now, and what runs later.
Freezing a page.An endless loop stops everything.Why JavaScript never waits by stopping.
The Network panel.Requests take time to arrive.The work that promises wait for.

By the end of this lesson you will be able to:

  • say why JavaScript does not stop to wait, and use setTimeout to run code later;
  • make a promise with new Promise, and say what pending, fulfilled and rejected mean;
  • chain then calls that pass values and promises along, and use finally;
  • handle a failure anywhere in a chain with one catch, and read an unhandled rejection;
  • wait for many promises with Promise.all, allSettled, race and any;
  • predict the order of synchronous code, promise callbacks and timers.

How to follow this lesson

In this lesson the order of the printed lines is the lesson. Before you run a block, write down the order you expect. The Run button waits for every timer and promise in the block, up to 3 seconds, and then shows the lines in the order they were printed.

In one line

A promise stands for a result that will arrive later; this lesson shows how to make one, chain work after it, catch its failures, and know what runs when.

Code that runs later

At a glance

A tea stall owner takes an order, puts the milk on the stove, and serves the next customer while it boils. Nobody stands staring at the pot. JavaScript works the same way.

Asynchronous work starts now and reports later. The function setTimeout(fn, ms) runs fn later, always after the code that is running has finished, even when ms is 0. Steps that must happen in order, written as callbacks inside callbacks, soon drift to the right like a staircase, which is hard to read and harder to fix.

Take a guess: Does setTimeout with a delay of 0 always wait 0 milliseconds?

JavaScript runs one line at a time, on one track. If it stopped on a line to wait two seconds for a server, nothing else could run for those two seconds: no clicks, no scrolling, no animation. So JavaScript has a different way to deal with things that take time. Such work is called asynchronous: it is started now, it finishes later, and your code is told when it does.

setTimeout

A function that runs a callback later: setTimeout(fn, ms) asks for fn to be run after at least ms milliseconds. It returns at once, so the lines after it carry on without waiting.

console.log("first");
setTimeout(() => console.log("timer"), 0);
console.log("last");
first
last
timer

The timer asked for 0 milliseconds, and still ran last. setTimeout does not run its callback; it hands it over to be run later. Later means: after the code that is running now has finished. Every callback for later work waits for the current code to end, however short its delay.

A timer cannot interrupt

Here the timer is due at once, but the code that is running keeps the track busy for 200 milliseconds with a loop that only watches the clock:

const start = Date.now();
setTimeout(() => console.log("timer, after the loop:", Date.now() - start >= 200), 0);
while (Date.now() - start < 200) {}
console.log("loop done");
loop done
timer, after the loop: true

The timer waited until the loop and the last line were finished. This is why code that keeps the track busy freezes a page, and why waiting must never be written as a loop. The DevTools step called such work, over 50 milliseconds on the main thread, a long task: while it runs, the page cannot draw or answer.

Cancelling, and the trouble with nesting

setTimeout returns an id, and clearTimeout(id) cancels the timer before it runs:

const id = setTimeout(() => console.log("never"), 100);
clearTimeout(id);
console.log("cancelled");
cancelled

When one piece of later work must follow another, callbacks have to be put inside callbacks. Three steps already make a staircase:

setTimeout(() => {
  console.log("order sent");
  setTimeout(() => {
    console.log("springs packed");
    setTimeout(() => {
      console.log("springs delivered");
    }, 10);
  }, 10);
}, 10);
order sent
springs packed
springs delivered

It works, and every new step adds another level. Handling a failure at any step would mean a check at every level. Promises, in the next section, write the same steps as a flat list.

Worked example 1

A railway announcement board shows the next train's message, then clears it 3 seconds later. In a test, the 3 seconds are shortened to 30 milliseconds. Show the message, clear it later, and print the board's text at each moment.

What we have: a message to show and a delay

What we need: the message shown now and cleared later

The plan: set the board's text at once, and use setTimeout to clear it after the delay

let board = "";
board = "Train 101 to Pune on platform 3";
console.log(`now: ${board}`);
setTimeout(() => {
  board = "";
  console.log(`later: \"${board}\"`);
}, 30);
console.log("the page carries on");
now: Train 101 to Pune on platform 3
the page carries on
later: ""

The message shows at once and is cleared 30 ms later, while the page carries on in between.

Check: "the page carries on" printed before the clearing, so nothing waited.

A path that fails: a loop that waits for 3 seconds before clearing the board. The page then freezes for 3 seconds, and no other train's message, click or animation can happen.

When you are stuck: code runs in an order you did not expect

Callbacks given to setTimeout run after the current code has finished, even with a delay of 0.

Number each console.log and write the order you expect before running.

A long loop delays every timer: nothing can interrupt running code.

Keep the id from setTimeout if you may need to cancel it.

Your turn

setTimeout(() => console.log("A"), 0);
console.log("B");
setTimeout(() => console.log("C"), 0);
console.log("D");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
B
D
A
C
  1. The two console.log lines at the top level run first: B, D.
  2. Then the timers, in the order they were set: A, C.

It prints B, D, A, C.

Why does setTimeout(f, 0) not run f at once?Tap to reveal
  1. setTimeout hands f over to be run later.
  2. Later is after the current code finishes.

Because a callback for later waits for the running code to end.

How do you stop a timer from running?Tap to reveal
  1. setTimeout returns an id.
  2. clearTimeout takes that id.

clearTimeout(id).

Did you know?

A number here, an object there

The value setTimeout gives back depends on where the code runs. In a browser, MDN says it is a positive integer that identifies the timer, to be passed to clearTimeout. In Node.js it is a Timeout object, which Node's documentation says is created internally and can be passed to clearTimeout too. Node adds that it makes no guarantees about the exact timing of callbacks.

Why it fits here: It warns about this topic's setTimeout: keep its result only to cancel the timer, since its type differs between browsers and Node.js.

Sources: MDN: Window.setTimeout(); Node.js documentation: Timers

Timers in hidden tabs

A page in a hidden tab gets fewer turns. Chrome 88 added what its team calls intensive throttling. When a page has been hidden for more than 5 minutes, has been silent for at least 30 seconds, and chains its timers five or more deep, the browser checks those timers only once per minute. Timers due within that minute then run together.

Why it fits here: It warns about this topic's timers: the delay is only a minimum, and a hidden tab may wait far longer than asked.

Source: Chrome for Developers: Heavy throttling of chained JS timers beginning in Chrome 88

In one line

JavaScript never stops to wait: asynchronous work starts now and reports later. setTimeout(fn, ms) runs fn later, always after the running code has finished, and nested callbacks for steps in order soon become a staircase.

What a promise is

At a glance

A token at a busy counter is a promise: no food yet, but a right to it later, or an apology if the kitchen runs out. JavaScript has the same idea as an object.

A promise stands for a result that is not ready yet. It starts pending, then is either fulfilled with a value or rejected with a reason, and never changes after that. The line new Promise((resolve, reject) => ...) runs its function at once, and then hears the value when it arrives.

Take a guess: Did JavaScript have promise libraries before promises joined the standard?

At a busy canteen counter, you pay and get a token. The token is not your dosa. It is a promise of a dosa: right now nothing is ready, later the dosa will come, or you will be told the batter has run out. Either way, you can wait anywhere you like, and the token tells you which way it went.

Promise

An object that stands for the result of asynchronous work. It is in one of three states: pending while the work goes on, fulfilled with a value when the work succeeds, or rejected with a reason, usually an error, when it fails. Once it is fulfilled or rejected, it is settled, and never changes again.

Many built-in functions give back promises, such as fetch in the next lessons. To make one yourself, write new Promise(...) with a function, called the executor, which receives two functions: resolve, to fulfil the promise, and reject, to reject it:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const p = new Promise((resolve) => setTimeout(() => resolve("tea ready"), 100));
p.then((msg) => console.log(msg));
console.log(p);
Promise { <pending> }
tea ready

At the moment p was printed, the 100 milliseconds had not passed, so it was pending. When the timer ran, resolve fulfilled it with tea ready, and the function given to then received that value. then is how you say what to do once the promise is fulfilled; the next section is about it.

The first line makes a small helper that this lesson uses often. wait(ms, value) gives a promise that is fulfilled with value after ms milliseconds, a stand-in for a slow server.

Two things about the executor

The executor runs at once, as soon as the promise is made; only the work it starts finishes later. And only the first call of resolve or reject counts; later calls are ignored, because a settled promise never changes:

const p = new Promise((resolve, reject) => {
  console.log("executor runs now");
  resolve(1);
  resolve(2);
  reject(new Error("too late"));
});
p.then((v) => console.log("value", v));
console.log("after new Promise");
executor runs now
after new Promise
value 1
StateMeansWhat runs
pendingthe work is still going onnothing yet
fulfilledit succeeded, with a valuethe callbacks given to then
rejectedit failed, with a reasonthe callbacks given to catch

Worked example 2

The upper floor orders springs. The workshop needs 50 milliseconds, and refuses orders of more than 10 springs. Write orderSprings(count), which returns a promise that is fulfilled with a message, or rejected with a RangeError, and place two orders.

What we have: a count, a delay, and a rule for refusing

What we need: a promise for each order, fulfilled or rejected

The plan: inside new Promise, start a timer; when it runs, reject for a count over 10, else resolve with the message

function orderSprings(count) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (count > 10) reject(new RangeError(`Cannot send ${count} springs at once`));
      else resolve(`${count} springs on their way`);
    }, 50);
  });
}
orderSprings(4).then((msg) => console.log(msg));
orderSprings(40).catch((err) => console.log(err.name, err.message));
console.log("orders placed");
orders placed
4 springs on their way
RangeError Cannot send 40 springs at once

The order for 4 is fulfilled; the order for 40 is rejected with a RangeError.

Check: "orders placed" printed first, as both orders were still pending then.

A path that fails: returning the message straight from inside the timer's callback. The callback's return value goes nowhere, and orderSprings itself has already returned undefined, before the timer ran.

When you are stuck: a promise never seems to do anything

Did the executor call resolve or reject? A promise that is never settled stays pending forever, without an error.

Did you give then a function? Without then or catch, nobody hears the result.

Print the promise right after making it: pending is normal there.

Remember that the executor runs at once; only what it starts is late.

Your turn

const p = new Promise((resolve) => {
  console.log("A");
  resolve("C");
});
p.then((v) => console.log(v));
console.log("B");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
A
B
C
  1. The executor runs at once: A.
  2. The last line runs next: B.
  3. then's callback runs after the current code: C.

It prints A, B, C.

Name the three states of a promise.Tap to reveal
  1. While the work goes on; when it succeeds; when it fails.

pending, fulfilled, rejected.

A promise was fulfilled with 1. What happens if its executor later calls reject?Tap to reveal
  1. A settled promise never changes.

Nothing: the call is ignored.

Did you know?

An open standard for promises

Promises were used in JavaScript before the language had them. MDN notes that the ecosystem had made many promise implementations long before promises became part of the language. Their authors agreed on Promises/A+, which calls itself an open standard for sound, interoperable JavaScript promises, and defines a promise as the eventual result of an asynchronous operation.

Why it fits here: It answers this topic's question: promise libraries came first, and agreed on a shared standard before JavaScript adopted promises.

Sources: MDN: Promise; Promises/A+

jQuery's Deferred, 2011

jQuery offered something like promises early on. Its Deferred object, added in version 1.5, is described as a chainable utility object that registers callbacks and relays the success or failure state of an asynchronous function. John Resig announced jQuery 1.5 on 31 January 2011, four years before ES2015 gave JavaScript its own Promise.

Why it fits here: It shows this topic's promise idea in older code: jQuery's Deferred played the same part long before the built-in Promise.

Sources: jQuery API Documentation: jQuery.Deferred(); Official jQuery Blog: jQuery 1.5 Released

In one line

A promise stands for a result that is not ready yet: pending, then fulfilled with a value or rejected with a reason, and never changed after that. new Promise((resolve, reject) => ...) runs its executor at once; then hears the value.

Chains of then

At a glance

A relay race passes one baton from runner to runner, each starting when the last arrives. A chain of then passes a value the same way.

The method then calls its function with the promise's value, and gives back a new promise for whatever that function returns, so steps chain from top to bottom. Return a promise to wait for it, or return a value to pass it on. Use finally for work that must happen either way, such as hiding a spinner.

Take a guess: Must an object be a real Promise for then and await to treat it as one?

then takes a function and calls it with the promise's value when the promise is fulfilled. Its useful secret is what it gives back: a new promise, for whatever the function returns. So a second then can follow the first, and a chain of steps reads as a list, top to bottom.

Promise.resolve(2)
  .then((n) => n * 10)
  .then((n) => n + 1)
  .then((n) => console.log(n));
21

Promise.resolve(2) makes a promise that is already fulfilled with 2. The first then turns 2 into 20, the second 20 into 21, and the last prints it. Each step receives what the step before it returned.

Returning a promise waits for it

If a step returns a promise, the chain waits for that promise and passes on its value, not the promise itself. This is what flattens the staircase of callbacks:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
wait(50, "order sent")
  .then((msg) => {
    console.log(msg);
    return wait(50, "springs packed");
  })
  .then((msg) => {
    console.log(msg);
    return wait(50, "springs delivered");
  })
  .then((msg) => console.log(msg));
order sent
springs packed
springs delivered

The same three steps as the nested timers of the first section, now one under another. Each step returns the next wait, and the next then runs only when that wait is over.

A step that forgets to return

A step that does its work and returns nothing passes undefined to the next:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
wait(10, 5)
  .then((n) => {
    n * 2;
  })
  .then((n) => console.log(n));
undefined

The braces made a body, so n * 2 was worked out and thrown away. Write return n * 2;, or an arrow without braces, (n) => n * 2.

finally

finally runs its function when the promise settles, fulfilled or rejected, without receiving the value, and passes the value on unchanged. It suits work that must happen either way, such as hiding a loading sign:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
console.log("loading...");
wait(30, "menu")
  .finally(() => console.log("loading sign hidden"))
  .then((v) => console.log("showing", v));
loading...
loading sign hidden
showing menu
A step returnsThe next step receives
a value, such as 21that value
a promisethe promise's value, once it is fulfilled
nothingundefined
(finally's function)the value from before finally, unchanged

Worked example 3

A ticket booking takes three slow steps: check the seat, take the payment, send the ticket. Each step needs the one before it. Write them as a chain with wait standing in for each slow step, and print a line after each.

What we have: three steps that must happen in order, each slow

What we need: the three lines in order, then a final line

The plan: start with the seat check, and in each then print, then return the next step's promise

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
wait(40, "seat 42 free")
  .then((seat) => {
    console.log(seat);
    return wait(40, "₹350 paid");
  })
  .then((payment) => {
    console.log(payment);
    return wait(40, "ticket sent");
  })
  .then((ticket) => console.log(ticket))
  .finally(() => console.log("booking finished"));
seat 42 free
₹350 paid
ticket sent
booking finished

The steps run in order, and the booking finishes once.

Check: each line appears only after the step before it, because each then returns the next promise.

A path that fails: starting all three waits at once, outside the chain. They then finish in whatever order their delays allow, and a ticket could be sent before the payment.

When you are stuck: a chain passes the wrong value

undefined means a step did not return: add return, or use an arrow without braces.

A promise where you expected a value means it was nested inside another value; return the promise itself.

Print inside each step, then(v => (console.log(v), v)), to see what passes along.

finally does not receive the value; then does.

Your turn

Promise.resolve(3)
  .then((n) => n + 1)
  .then((n) => {
    console.log(n);
  })
  .then((n) => console.log(n));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4
undefined
  1. 3 + 1 = 4, printed by the second step.
  2. The second step returned nothing, so the third receives undefined.

It prints 4, then undefined.

What does then give back?Tap to reveal
  1. A new promise, for what its function returns.

A new promise, so another then can follow.

A step returns wait(100, "x"). When does the next step run, and with what?Tap to reveal
  1. The chain waits for a returned promise.
  2. It passes on the promise's value.

After 100 ms, with "x".

Did you know?

Anything with a then

A promise chain accepts more than real promises. Promises/A+ defines a thenable as an object or function that defines a then method, and MDN explains that all promise-like objects implement this thenable interface. So returning any thenable from then makes the chain wait for it, whichever library made it.

Why it fits here: It answers this topic's question: then looks only for a then method, so a thenable from any library works.

Sources: Promises/A+; MDN: Promise

finally, since 2018

The finally step is younger than then and catch. The 2018 edition of the standard defines Promise.prototype.finally, which MDN describes as scheduling a function to be called when the promise is settled, whether fulfilled or rejected. MDN adds that it lets you avoid duplicating the same code in both a then and a catch.

Why it fits here: It dates this topic's finally: the clean-up step that runs either way joined the standard in 2018.

Sources: ECMAScript 2018 Language Specification; MDN: Promise.prototype.finally()

In one line

then calls its function with the promise's value and gives back a new promise for whatever it returns, so steps chain top to bottom. Return a promise to wait for it, return a value to pass it on, and use finally for work that happens either way.

Failures, caught in one place

At a glance

A factory line has one inspector at the end, who catches a fault from any station along the way. A chain of promises can have one catch in the same way.

The method catch hears a rejection, and an error thrown inside any then becomes one, skipping the steps after it. Put one catch at the end of a chain; a catch in the middle can repair the chain and let it carry on. A rejection with no catch at all is reported as Uncaught.

Take a guess: What does Node.js do today when a promise is rejected and nothing catches it?

A rejected promise carries a reason instead of a value, usually an Error object. catch is the then of failures: it takes a function, and calls it with the reason when the promise is rejected.

const p = Promise.reject(new Error("no milk"));
p.catch((err) => console.log("caught:", err.message));
caught: no milk

One catch for a whole chain

A failure anywhere in a chain skips every then after it, until it reaches a catch. And an error thrown inside a then, by a slip or on purpose, turns that step's promise into a rejected one. So one catch at the end of a chain handles every step:

Promise.resolve(1)
  .then((v) => {
    throw new Error("oops " + v);
  })
  .then(() => console.log("never runs"))
  .catch((err) => console.log(err.message))
  .finally(() => console.log("done"));
oops 1
done

The throw in the first step rejected the chain. The second step was skipped, the catch received the error, and finally ran last. This is the try and catch of the errors lesson, spread over time: the work in the thens, the handling at the end.

Carrying on after a failure

catch also gives back a promise, for what its function returns. A catch in the middle of a chain can therefore repair a failure and let the steps after it carry on, with a value of its own:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const price = Promise.reject(new Error("price list down"));
price
  .catch((err) => {
    console.log("using the old price:", err.message);
    return 15;
  })
  .then((p) => console.log(`tea costs ₹${p}`));
using the old price: price list down
tea costs ₹15

A rejection nobody catches

A rejected promise with no catch anywhere is an unhandled rejection. It is reported like an uncaught error, which it is:

Promise.reject(new Error("no milk"));
Uncaught Error: no milk
    at line 1

The block above shows how this page words it. Chrome's own Console adds two words, so that you can tell where it came from: Uncaught (in promise) Error: no milk. The program carries on, and the failure itself is lost: the page probably shows a spinner forever, or an empty list. Every chain needs a catch at its end, or must be returned to a caller that has one.

In a chainWhat happens
a step throws, or returns a rejected promisethe steps after it are skipped, down to the next catch
catch(fn)fn receives the reason; what fn returns goes on down the chain
a catch that throws againthe chain stays rejected, for a later catch
no catch at allan unhandled rejection: Uncaught Error in the Console

Worked example 4

A school's results page loads a student's marks in two steps: find the roll number, then load the marks. The second step fails for roll number 0, which does not exist. Write the chain so that any failure shows Could not load the results and the reason, once.

What we have: two steps that may each fail

What we need: the marks, or one clear message

The plan: chain the two steps, throw a RangeError in the second for roll 0, and put one catch at the end

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
function loadResults(roll) {
  return wait(30, roll)
    .then((r) => {
      if (r === 0) throw new RangeError(`No student with roll number ${r}`);
      return wait(30, { roll: r, total: 412 });
    })
    .then((marks) => `Roll ${marks.roll}: ${marks.total} marks`)
    .catch((err) => `Could not load the results: ${err.message}`);
}
loadResults(17)
  .then(console.log)
  .then(() => loadResults(0))
  .then(console.log);
Roll 17: 412 marks
Could not load the results: No student with roll number 0

Roll 17 shows 412 marks; roll 0 shows one clear message.

Check: for roll 0, the step that builds the marks line was skipped, straight to the catch.

A path that fails: a catch after every step. The first catch turns the failure into a value, so the next step runs with that message as if it were the marks, and the page shows nonsense.

When you are stuck: a failure is not caught, or caught in the wrong place

Uncaught Error in the Console means a rejected promise had no catch: add one at the end of the chain.

A step that ran after a failure means a catch above it repaired the chain: check what that catch returns.

Throw again from a catch that cannot handle the failure, so that a later catch sees it.

Print err.message, not the whole error, to see the reason.

Your turn

Promise.resolve("a")
  .then(() => {
    throw new Error("b");
  })
  .then(() => console.log("c"))
  .catch((e) => console.log(e.message))
  .then(() => console.log("d"));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
b
d
  1. The first then throws b; the c step is skipped.
  2. catch prints b and returns nothing, so the chain carries on.
  3. The last then runs: d.

It prints b, then d.

What does an error thrown inside a then do to the chain?Tap to reveal
  1. It rejects that step's promise.
  2. The following thens are skipped, down to a catch.

It rejects the chain, down to the next catch.

What appears in the Console for a rejected promise that has no catch?Tap to reveal
  1. It is reported like an uncaught error.

An Uncaught Error line with the reason.

Did you know?

Node stops on a forgotten rejection

Node.js changed its mind about forgotten promises. As of Node.js 15, its release notes say, the default mode for an unhandled rejection changed from warn to throw. Unless the program sets an unhandledRejection hook, the rejection is raised as an uncaught exception, which ends the program. A missing catch now fails loudly.

Why it fits here: It answers this topic's question: a rejection with no catch now stops a Node.js program, so a final catch matters.

Source: Node.js blog: Node.js 15.0.0

An event for forgotten rejections

Browsers announce a rejection that nobody caught. MDN explains that the unhandledrejection event is sent to the global scope when a promise with no rejection handler is rejected, which helps with debugging and with fallback error handling. The HTML standard fires it at the global object as a PromiseRejectionEvent, which carries the promise and the reason.

Why it fits here: It gives this topic's Uncaught report a hook: a page can listen for unhandledrejection and log every forgotten failure.

Sources: MDN: Window: unhandledrejection event; WHATWG: HTML Standard, unhandled promise rejections

In one line

catch hears a rejection, and an error thrown in any then becomes one, skipping the steps after it. Put one catch at the end of a chain; a catch in the middle can repair it. A rejection with no catch is reported as Uncaught.

Many promises at once

At a glance

A family going out does not wait for each person to dress one after another; everyone gets ready at once, and they leave when the last is ready. Independent work in code can be started and waited for together too.

Promise.all gives every value in order, or the first failure. Promise.allSettled gives a report on each promise, whatever happened. Promise.race gives the first to settle, and Promise.any the first to succeed. Starting the work together is what saves the time; waiting together only collects the results.

Take a guess: Is there now a way to get a promise and its resolve function in one call?

A chain runs its steps one after another. Often the steps do not depend on each other: a page needs the menu, the prices and the opening hours, from three places. Waiting for each in turn wastes time. Start them all, and wait for them together.

Promise.all: every one, or the first failure

Promise.all takes an array of promises and gives one promise, fulfilled with an array of all their values once every one is fulfilled. The values come in the order of the inputs, not the order they finished in:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
Promise.all([wait(200, "menu"), wait(50, "prices")]).then((values) => console.log(values));
[ 'menu', 'prices' ]

prices was ready first, and still comes second, where it was in the array. And the whole took about 200 milliseconds, the slowest of the two, not 250. If any of the promises is rejected, all is rejected at once with that reason, and the other values are not given:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, why) => new Promise((resolve, reject) => setTimeout(() => reject(new Error(why)), ms));
Promise.all([wait(50, "menu"), fail(20, "prices down")])
  .then((values) => console.log(values))
  .catch((err) => console.log("failed:", err.message));
failed: prices down

allSettled, race and any

Three more ways to wait, for other needs. Promise.allSettled waits for every promise and reports each one, fulfilled or rejected, so one failure does not hide the other results:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, why) => new Promise((resolve, reject) => setTimeout(() => reject(new Error(why)), ms));
Promise.allSettled([wait(30, "menu"), fail(10, "prices down")]).then((results) => {
  for (const r of results) console.log(r.status, r.status === "fulfilled" ? r.value : r.reason.message);
});
fulfilled menu
rejected prices down

Promise.race settles as soon as the first of its promises settles, either way. Promise.any waits for the first one to be fulfilled, and ignores failures unless every one fails:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, why) => new Promise((resolve, reject) => setTimeout(() => reject(new Error(why)), ms));
Promise.race([wait(200, "slow server"), wait(50, "fast server")]).then((v) => console.log("race:", v));
Promise.any([fail(10, "mirror 1 down"), wait(60, "mirror 2")]).then((v) => console.log("any:", v));
race: fast server
any: mirror 2
MethodFulfilled whenRejected whenGood for
Promise.allevery one is fulfilled: all the values, in orderthe first one failsdata that a page needs all of
Promise.allSettledevery one has settled: a report for eachneverdoing many things and listing what failed
Promise.racethe first to settle is fulfilledthe first to settle is rejecteda time limit, raced against a timer
Promise.anythe first one is fulfilledevery one failsthe fastest of several copies of the same data

Worked example 5

The canteen's page shows the menu, but should give up after 100 milliseconds and show a message, rather than spin forever. Race the slow menu against a timer that rejects, and catch the failure.

What we have: a slow menu and a time limit

What we need: the menu if it is quick enough, else a message

The plan: a timeout(ms) that rejects after ms, raced against the menu; catch shows the message

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const timeout = (ms) => new Promise((resolve, reject) => setTimeout(() => reject(new Error(`no answer in ${ms} ms`)), ms));
function showMenu(menuTime) {
  return Promise.race([wait(menuTime, "thali, poha, chai"), timeout(100)])
    .then((menu) => `Menu: ${menu}`)
    .catch((err) => `Menu unavailable: ${err.message}`);
}
showMenu(30).then(console.log);
showMenu(300).then(console.log);
Menu: thali, poha, chai
Menu unavailable: no answer in 100 ms

A quick menu is shown; a slow one gives Menu unavailable after 100 ms.

Check: the second menu would have taken 300 ms, and the timer rejected first.

A path that fails: Promise.all with the timer. all waits for every promise, so the fast menu would still wait for the timer, and the timer's rejection would always win.

When you are stuck: waiting for several promises goes wrong

One failure loses every value? That is Promise.all: use allSettled to keep the others.

Values in the wrong place? all keeps the order of its inputs, not of finishing.

Pass promises, not functions: wait(50), with brackets, starts the work.

Steps that need each other's results belong in a chain, not in all.

Your turn

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
Promise.all([wait(60, 1), wait(20, 2), wait(40, 3)]).then((v) => console.log(v));
Promise.race([wait(60, "x"), wait(20, "y")]).then((v) => console.log(v));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
y
[ 1, 2, 3 ]
  1. race settles at 20 ms with y.
  2. all waits for the slowest, 60 ms, and keeps the order 1, 2, 3.

It prints y, then [ 1, 2, 3 ].

Which method reports every promise's result even when some fail?Tap to reveal
  1. all stops at the first failure.
  2. One method waits for all to settle.

Promise.allSettled.

How long does Promise.all([wait(100), wait(300)]) take?Tap to reveal
  1. Both started at once.
  2. all waits for the slowest.

About 300 ms, not 400.

Did you know?

Resolve from outside

A newer method hands over a promise with its controls. MDN describes Promise.withResolvers() as returning an object with a new promise and the two functions that resolve or reject it, so code outside the promise's own function can settle it. TC39's list of finished proposals names it, by Peter Klecha, and MDN shows it working across browsers since March 2024.

Why it fits here: It answers this topic's question: one call now gives a promise together with its resolve and reject functions.

Sources: MDN: Promise.withResolvers(); TC39: Finished Proposals

Promise.try, 2025

Starting a chain with code that may throw got easier in 2025. MDN describes Promise.try as taking a callback of any kind, one that returns or throws, at once or later, and resolving its result to a promise, so even a thrown error becomes a rejection for catch. MDN shows it working in the latest browsers since January 2025, and TC39 lists it as finished.

Why it fits here: It adds a tool for this topic's chains: Promise.try turns any function's result, or its error, into a promise.

Sources: MDN: Promise.try(); TC39: Finished Proposals

In one line

Start independent work together and wait together: Promise.all for every value in order (or the first failure), allSettled for a report on each, race for the first to settle, any for the first to succeed.

What runs next: the event loop

At a glance

A busy post office serves the person at the counter to the end, then quickly handles any notes that person left, and only then calls the next number. JavaScript's event loop keeps the same order.

It runs the current code to its end, then every waiting promise callback, the microtasks, and then one task, such as a timer or a click, before going round again. So the order is always the same: running code, microtasks, the next task. A promise callback therefore runs before a timer of 0 milliseconds.

Take a guess: Can your own code put a callback in the microtask queue, without a promise?

You have now seen the same order many times: the running code first, then promise callbacks, then timers. The rule behind that order is short, and it lets you work out any of these puzzles on paper.

Event loop

The rule by which JavaScript chooses what runs next. It runs one piece of work to its end, then every waiting promise callback, then takes the next waiting task, such as a timer's callback or a click, and goes round again.

Three kinds of work take part. MDN calls the waiting promise callbacks microtasks, and the waiting timers and events tasks.

Kind of workExamplesWhen it runs
the running codethe script itself, or one task's callbackto its end, and nothing interrupts it
microtaskscallbacks of then, catch and finallyall of them, right after the running code, new ones included
taskstimers' callbacks, clicks and other eventsone at a time, with all the microtasks after each
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("sync");
sync
promise
timeout

The running code goes first: it sets the timer, sets the then, and prints sync. Then come the microtasks: promise. Then the next task: timeout. The timer was set first, with a delay of 0, and still came last.

New microtasks made by a microtask join the same round, so a whole chain finishes before any timer:

setTimeout(() => console.log("timer"), 0);
Promise.resolve()
  .then(() => console.log("step 1"))
  .then(() => console.log("step 2"))
  .then(() => console.log("step 3"));
step 1
step 2
step 3
timer

Two chains take turns, because each step puts the next one at the back of the microtask queue:

Promise.resolve().then(() => console.log(1)).then(() => console.log(2));
Promise.resolve().then(() => console.log("a")).then(() => console.log("b"));
1
a
2
b

A puzzle, worked on paper

Here is a harder one. Follow the table under it line by line, before you trust the output:

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => {
  console.log("C");
  setTimeout(() => console.log("D"), 0);
  Promise.resolve().then(() => console.log("E"));
});
console.log("F");
A
F
C
E
B
D
RoundWhat happensPrinted
running codeA; timer B is queued as a task; the then is queued as a microtask; FA, F
microtasksC; timer D is queued as a task; E is queued as a microtask, and runs in this same roundC, E
first tasktimer B, the earlier timerB
second tasktimer DD

Worked example 6

A shop's page prints what it does as it loads. Predict the order of these four lines before running: showing the page, filling in the menu from a promise that is ready, an advert from a 0 ms timer, and a last line that says the page is ready.

What we have: four lines: two in the running code, one in a then, one in a timer

What we need: the order, worked out from the event loop

The plan: the running code first (two lines), then the microtask (the menu), then the task (the advert)

console.log("show the page");
Promise.resolve("menu").then((v) => console.log("fill", v));
setTimeout(() => console.log("ad banner"), 0);
console.log("page ready");
show the page
page ready
fill menu
ad banner

The order is show the page, page ready, fill menu, ad banner.

Check: the printed order matches the three rounds exactly.

A path that fails: reading from top to bottom, and expecting fill menu in second place. A then's callback never runs in the middle of the running code, even when its promise is already fulfilled.

When you are stuck: you cannot work out the order

Make three columns: running code, microtasks, tasks.

Go down the code once, writing each callback in its column, and each console.log as printed.

Then empty the microtasks, including any new ones they add.

Then take one task, empty the microtasks again, and repeat.

Your turn

setTimeout(() => console.log("t1"), 0);
Promise.resolve().then(() => console.log("p1"));
setTimeout(() => console.log("t2"), 0);
Promise.resolve().then(() => console.log("p2"));
console.log("s");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
s
p1
p2
t1
t2
  1. The running code prints s.
  2. The microtasks run in order: p1, p2.
  3. The timers run in order: t1, t2.

It prints s, p1, p2, t1, t2.

Why does a then's callback run before a timer of 0 ms?Tap to reveal
  1. then's callbacks are microtasks.
  2. All microtasks run before the next task.

Because microtasks run before the next task.

Can a timer's callback run in the middle of a loop?Tap to reveal
  1. Running code is never interrupted.

No: it waits until the running code ends.

Did you know?

The post that explained the order

One blog post became the classic explanation of this topic. On 17 August 2015 Jake Archibald published Tasks, microtasks, queues and schedules. It explains that microtasks are usually scheduled for things that should happen straight after the code that is running, such as reacting to a batch of actions, without the cost of a whole new task.

Why it fits here: It points to a classic guide on this topic's order: running code, then microtasks, then the next task.

Source: Jake Archibald: Tasks, microtasks, queues and schedules

A microtask of your own

Code can add to the microtask queue directly. The HTML standard's queueMicrotask() lets a page schedule a callback on the microtask queue, to run once all the code running now has finished. MDN calls it queuing a microtask to be executed at a safe time, before control returns to the browser's event loop.

Why it fits here: It answers this topic's question: queueMicrotask puts a callback in the same queue as promise callbacks, with no promise at all.

Sources: WHATWG: HTML Standard, microtask queuing; MDN: Window.queueMicrotask()

In one line

The event loop runs the current code to its end, then every promise callback, then one task, such as a timer or a click, and goes round again. So the order is always: running code, microtasks, the next task.

Where it is used

Anything that takes time in a program goes through these ideas. Here is where each one does its work.

What you learnedWhere it is usedA real example
setTimeoutdelays and clearing things latera message that disappears after 3 seconds
promiseswork that finishes latera file from a server, as the fetch lesson shows
then chainssteps that must happen in ordercheck the seat, take the payment, send the ticket
catch and finallyfailures, and clearing up either wayan error message instead of an endless spinner
Promise.all and allSettledmany independent pieces of datathe menu, the prices and the hours loaded together
Promise.racetime limitsgiving up on a slow server
the event looppages that never freezesplitting long work so that clicks can get through

Mistakes and debugging

These are the slips that people meet most often with promises. Every output below is the real one, from the code shown.

1. Using the result on the next line

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
let springs;
wait(10, "4 springs").then((s) => {
  springs = s;
});
console.log(springs);
undefined

No error: the next line ran long before the promise was fulfilled. This is the empty box of the scene. The fix: use the value inside the then, or with await, in the next lesson.

2. A step that forgets to return its promise

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
wait(10, 1)
  .then((n) => {
    wait(10, n + 1);
  })
  .then((n) => console.log(n));
undefined

No error: the chain did not wait for the inner promise, and received nothing. The fix: return wait(10, n + 1);.

3. A failure that escapes the catch

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
wait(10, 1)
  .then((v) => {
    wait(10, v).then(() => {
      throw new Error("inner");
    });
  })
  .catch((e) => console.log("caught", e.message));
Uncaught Error: inner
    at line 5

The catch never saw it: the inner chain was not returned, so it is not part of the outer chain. The fix: return the inner promise, so that one catch covers both.

4. Calling the function instead of passing it

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const show = () => console.log("shown");
wait(50).then(show());
console.log("next line");
shown
next line

No error: show() ran at once, and then received its result, undefined, which it ignores. The fix: then(show), with no brackets.

5. Functions given to Promise.all

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
Promise.all([wait, wait]).then((v) => console.log(v.length, typeof v[0]));
2 function

No error: all treats anything that is not a promise as a finished value, so nothing waited. The fix: call them, Promise.all([wait(50), wait(80)]).

6. A catch in the middle that hides the failure

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
wait(10, "menu")
  .then(() => {
    throw new Error("no menu today");
  })
  .catch((e) => console.log(e.message))
  .then((menu) => console.log(`showing ${menu}`));
no menu today
showing undefined

No uncaught error: the catch handled the failure and returned nothing, so the chain carried on with undefined. The fix: put the catch last, or throw again from it, as the errors lesson advised, when the steps after it cannot go on.

The debugging corner: look inside the chain

Add a step that prints and passes the value on, then((v) => (console.log(v), v)), between any two steps. A value of undefined shows the step before it forgot to return. Then make sure the chain ends in a catch, so that no failure is lost.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code

// a promise: pending, then fulfilled or rejected, once
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

// a chain: return to pass on; one catch; finally either way
wait(20, 2)
  .then((n) => wait(20, n * 10))
  .then((n) => {
    if (n > 10) throw new RangeError(`too many: ${n}`);
    return n;
  })
  .catch((err) => `refused, ${err.message}`)
  .finally(() => console.log("chain finished"))
  .then((v) => console.log(v));

// together: every value, in order of the inputs
Promise.all([wait(30, "menu"), wait(10, "prices")]).then((v) => console.log(v));

// the order: running code, microtasks, tasks
setTimeout(() => console.log("task"), 0);
Promise.resolve().then(() => console.log("microtask"));
console.log("running code");
running code
microtask
task
[ 'menu', 'prices' ]
chain finished
refused, too many: 20
When you seeIt meansLook at
undefined where a result should bethe line ran before the promise settleduse the value inside then
undefined in the next stepa step did not returnreturn, or an arrow without braces
Uncaught Error from a promisea rejection with no catcha catch at the end, and returned inner promises
a spinner that never stopsa promise never settled, or a failure unhandledresolve or reject on every path; a catch; finally
a page that freezesa long loop in the running codenothing can run until it ends
lines in a surprising orderthe event looprunning code, microtasks, tasks

The story: A slip from the courier

You rewrite the order. Sending for the springs now gives back a promise at once, and the script carries on, so every clock keeps time. When the promise is kept, the springs are fitted, then tested, one step after the other. When the courier fails, a single catch writes the reason in the log.

Today the courier was an hour late again, and not one clock lost a second.

Master Verge reads the log, where the late parcel is recorded and nothing else. "A promise lets you plan for something that has not happened yet," he says. "That is most of what a city runs on."

Reagents gathered: asynchronous, promise, then, catch, Promise.all, event loop.

Sources