Loading video player…

Watch Four Promises Settle

In this video, the Lindqvists’ blinds go offline, and you watch four promises settle side by side. A promise settles when it’s fulfilled or rejected. Promise.all() and three related methods each settle at their own moment, with their own result, while every device runs to its end.

Key Points

  • Promise.all() rejects at the first rejection, with that promise’s error, or fulfills once every promise fulfills. When the blinds reject at two seconds, it rejects at two seconds with Blinds offline.
  • Promise.race() settles the way the first promise to settle does, fulfilled or rejected. With all four devices, the lights win at one second. Without the lights, the blinds settle first, so it rejects at two seconds.
  • Promise.any() settles with the first promise to fulfill, if one does, and skips rejections on the way. Without the lights, it skips the blinds and fulfills at three seconds with Heating on. The next lesson, Report Which Devices Worked, shows what happens when none does.
  • Promise.allSettled() waits until every promise has settled, fulfilled or rejected, and doesn’t reject because a device failed. It fulfills at six seconds, after the kettle, with an array of four results in the order you listed the devices. Each result has a status, and the blinds’ result holds their error.
  • No method stops a device. After Promise.all() rejects at two seconds, the heating still turns on at three seconds and the kettle still boils at six. Nothing tells them to stop.

The Code

In devices.mjs, the blinds now go offline. openBlinds() waits two seconds and throws an Error, which rejects its promise:

Language: JavaScript Filename: devices.mjs
import { setTimeout as delay } from "node:timers/promises";

export async function turnOnLights() {
  await delay(1000);
  return "Lights on";
}

export async function openBlinds() {
  await delay(2000);
  throw new Error("Blinds offline");
}

export async function warmUpHeating() {
  await delay(3000);
  return "Heating on";
}

export async function boilKettle() {
  await delay(6000);
  return "Kettle boiled";
}

The script starts the four devices and watches each device’s promise and each method’s promise. The seconds() helper is new: it gives the time since the script started, to a tenth of a second.

The watch() function logs that time, a label and the value when a promise fulfills, or the error’s message when it rejects. It doesn’t await anything. It attaches its .then() and .catch() callbacks and returns right away. So the script sets up every watch before anything settles, and each callback logs the moment its promise settles:

Language: JavaScript Filename: watch_settle.mjs
import {
  turnOnLights,
  boilKettle,
  openBlinds,
  warmUpHeating,
} from "./devices.mjs";

const start = Date.now();
const seconds = () => ((Date.now() - start) / 1000).toFixed(1);

function watch(label, promise) {
  promise
    .then((value) => console.log(`${seconds()} s: ${label} fulfilled:`, value))
    .catch((error) => console.log(`${seconds()} s: ${label} rejected: ${error.message}`));
}

const routine = [turnOnLights, boilKettle, openBlinds, warmUpHeating];
const running = routine.map((startDevice) => startDevice());
for (const device of running) {
  watch("device", device);
}

watch("all()", Promise.all(running));
watch("race()", Promise.race(running));
watch("any()", Promise.any(running));
watch("allSettled()", Promise.allSettled(running));

Here’s what the script printed. Each line prints as its promise settles, and the blinds’ result holds their error with its stack trace:

Language: Text
1.0 s: device fulfilled: Lights on
1.0 s: race() fulfilled: Lights on
1.0 s: any() fulfilled: Lights on
2.0 s: device rejected: Blinds offline
2.0 s: all() rejected: Blinds offline
3.0 s: device fulfilled: Heating on
6.0 s: device fulfilled: Kettle boiled
6.0 s: allSettled() fulfilled: [
  { status: 'fulfilled', value: 'Lights on' },
  { status: 'fulfilled', value: 'Kettle boiled' },
  {
    status: 'rejected',
    reason: Error: Blinds offline
        at openBlinds (file:///tmp/morning/devices.mjs:10:9)
  },
  { status: 'fulfilled', value: 'Heating on' }
]

Next, in Report Which Devices Worked, you’ll read the results of Promise.allSettled() and pair each device with its status.

00:00 In the last lesson, you started all four devices with .map() and waited for them with Promise.all(). The statuses came back in the order you listed the devices.

00:11 But the Lindqvists’ blinds don’t always answer. So today, openBlinds() waits two seconds and then throws an error that says the blinds are offline, which rejects its promise.

00:22 In this video, you’ll watch four promises settle side by side. A promise settles when it’s fulfilled or rejected. You’ll see when Promise.all() and three related methods settle, and with what.

00:36 To see when each promise settles, the script needs a clock and a function that watches each promise. A new helper, seconds(), gives the time since the script started, to a tenth of a second.

00:49 A new function, watch(), takes a label and a promise. When the promise fulfills, the .then() callback logs the time, the label and the value.

00:59 When it rejects, the .catch() callback logs the error’s message. But watch() doesn’t await anything. It attaches its two callbacks and returns right away.

01:10 So the script sets up every watch before anything settles, and each callback logs when its promise settles.

01:18 Then the script starts the four devices with .map(), as before, and watches each one with the label "device". Run it, and each device settles on its own timeline.

01:29 The lights fulfill at one second. The blinds reject at two. The heating fulfills at three, and the kettle at six.

01:40 Now add a watch for Promise.all(), on the same four promises. It fulfills only if every device fulfills. Run it again. At two seconds, the moment the blinds reject, Promise.all() rejects with the same error.

01:56 Look at the two lines after it, though. The heating still turns on at three seconds, and the kettle still boils at six. Promise.all() stopped waiting.

02:06 It didn’t stop the devices. Nothing tells them to stop, so they run to the end.

02:13 Next comes Promise.race(). It settles the way the first promise settles, fulfilled or rejected. Add a watch for it, and run it. The lights settle first, so Promise.race() fulfills at one second, with Lights on.

02:28 Promise.race() comes back later, when the kettle gets a deadline.

02:32 Say the lights are already on, so Saga takes them out of the routine. Now the blinds are the fastest device. Your turn: pause the video and predict what Promise.race() settles with now.

02:51 Promise.race() settles at two seconds, rejected with the blinds’ error. Promise.race() takes whatever comes first, even a rejection.

03:01 Promise.any() waits for the first promise to fulfill instead, and skips rejections on the way. It fits when one success is enough, like Erik checking that at least one device answers.

03:13 Add a watch for it, and run it again. Promise.any() skips the blinds’ rejection and waits for the heating. It fulfills at three seconds, with Heating on.

03:25 Put the lights back, and add a watch for Promise.allSettled(), the last of the four methods. It waits until every promise has settled. It never rejects because a device failed.

03:37 So it settles at six seconds, after the kettle. Its value is an array of four results, one per device, in the order you listed them. Each result has a status, fulfilled or rejected.

03:51 The blinds’ result holds their error, with its stack trace.

03:56 Each method settles at its own moment, by its own rule. Promise.all() settles at the first rejection, or once every promise fulfills. Promise.race() settles with the first promise to settle.

04:09 Promise.any() settles with the first to fulfill, if one does. Report Which Devices Worked shows what happens when none does. Promise.allSettled() waits for them all.

04:21 None of them stops a device that’s still running.

04:25 So this morning, only Promise.allSettled() can tell you which devices worked. Next, in Report Which Devices Worked, you’ll read its results and pair each device with its status.

Become a Member to join the conversation.