Report Which Devices Worked

In the last video, the Lindqvists’ blinds went offline, and only Promise.allSettled() waited for every device and told you something about each one. It fulfilled with an array of four results, one per device. But an array of objects isn’t a report Erik and Saga can read over breakfast.

In this lesson, you’ll turn those results into a morning report that pairs each device with its status or the reason it failed. You’ll also see how Promise.any() fails when no device works and what each of the four methods does when there’s nothing to wait for.

Read One Result at a Time

For each device, a report needs to say whether it worked and what it said. Before you can pull those out, you need to know where they live in the result objects.

If you’re following along from the video, you already have the version of devices.mjs where the blinds go offline. If not, save this in your morning folder. openBlinds() waits two seconds and then throws, 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";
}

Now create morning_report.mjs. It starts the four devices as before, waits for all of them with Promise.allSettled(), and logs the lights’ result and two parts of the blinds’ result:

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

const routine = [turnOnLights, boilKettle, openBlinds, warmUpHeating];
const running = routine.map((startDevice) => startDevice());
const results = await Promise.allSettled(running);

console.log("Lights:", results[0]);
console.log(`Blinds: ${results[2].status}`);
console.log(`Reason: ${results[2].reason.message}`);

Run it, and after about six seconds, once the kettle has boiled, all three lines appear:

Language: Shell
$ node morning_report.mjs
Lights: { status: 'fulfilled', value: 'Lights on' }
Blinds: rejected
Reason: Blinds offline

Every result is an object with a status property, which holds the string "fulfilled" or "rejected". A fulfilled result also has a value property with what the device returned. A rejected result has a reason property instead, which holds what the device threw.

Here, that’s the whole Error object, so .reason.message gives you its text, "Blinds offline", without the stack trace you saw in the video.

The await on Promise.allSettled() didn’t throw, even though the blinds failed. That’s the method’s whole job. It turns a device’s failure into a result in the array, so there’s no error for you to catch.

Pair Each Result With Its Device

The results don’t say which device they belong to. They don’t need to, because Promise.allSettled() keeps the results in the order of the promises you gave it, as Promise.all() did in the first lesson. So results[2] belongs to routine[2], the blinds, even though the blinds settled before the heating and the kettle.

That means the index is the link between a result and its device. The callback you pass to .map() receives each element’s index as its second argument, so you can look up the device in routine while you read its result.

To name the device, use the .name property of its function. For named function declarations like these four, .name holds the name the function was declared with, such as "openBlinds".

Replace the three console.log() lines with a report that has one line per device:

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

const routine = [turnOnLights, boilKettle, openBlinds, warmUpHeating];
const running = routine.map((startDevice) => startDevice());
const results = await Promise.allSettled(running);

const report = results.map((result, index) => {
  const device = routine[index].name;
  if (result.status === "fulfilled") {
    return `${device}: ${result.value}`;
  }
  return `${device}: failed (${result.reason.message})`;
});
console.log(report);

The callback checks result.status first, because only a fulfilled result has a value and only a rejected one has a reason. Run the script again:

Language: Shell
$ node morning_report.mjs
[
  'turnOnLights: Lights on',
  'boilKettle: Kettle boiled',
  'openBlinds: failed (Blinds offline)',
  'warmUpHeating: Heating on'
]

That’s the report the Lindqvists wanted. Three devices worked, and you can see why the blinds failed. The lines come in the order the routine lists the devices. If you use Promise.all() here, then the await throws at two seconds with the blinds’ error, and you lose the other three statuses.

Check Whether Anything Answered

Sometimes you don’t need a full report. In the video, Erik only wanted to know whether at least one device answered, and Promise.any() fits that. It fulfills with the value from the first device to succeed and skips failures on the way. With all four devices, it fulfills at one second with "Lights on". But what does it do when every device fails?

On Saturdays, the Lindqvists’ routine only opens the blinds, so Erik’s check has only one device to wait for. Save this as anything_working.mjs. It catches the rejection with try…catch, as you would around any await that can fail:

Language: JavaScript Filename: anything_working.mjs
import { openBlinds } from "./devices.mjs";

const saturday = [openBlinds];
const running = saturday.map((startDevice) => startDevice());

try {
  const first = await Promise.any(running);
  console.log(`Working: ${first}`);
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}

In the video, Promise.all() rejected with the blinds’ own error. So did Promise.race() in the run where the lights were left out and the blinds settled first. Run node anything_working.mjs, and after two seconds, the catch block logs a different error:

Language: Shell
$ node anything_working.mjs
AggregateError: All promises were rejected

It isn’t the blinds’ error. Promise.any() rejects only once every promise has rejected, so it usually has several errors in hand and no reason to pick one. It rejects with a new error that holds all of them instead, even when there’s only one.

That new error is an AggregateError, an error that collects other errors. Its .message only says that all the promises were rejected. The actual reasons are in its .errors property, an array with one rejection reason per promise, in the order you passed the promises in.

A reason can be any value, but the devices always reject with Error objects, so .message works on each one here. Add a line to the catch block to read them:

Language: JavaScript Filename: anything_working.mjs
import { openBlinds } from "./devices.mjs";

const saturday = [openBlinds];
const running = saturday.map((startDevice) => startDevice());

try {
  const first = await Promise.any(running);
  console.log(`Working: ${first}`);
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
  console.log(error.errors.map((reason) => reason.message));
}

Run it again, and the second line shows why the blinds failed:

Language: Shell
$ node anything_working.mjs
AggregateError: All promises were rejected
[ 'Blinds offline' ]

So when Promise.any() rejects, log or report error.errors as well as error.message. Otherwise, Erik learns that nothing worked but never finds out why.

If you’d like to test how well you can tell Promise.any() and Promise.race() apart, then click this button to ask the mentor for a situation to think through, with this section attached:

Start a Routine With No Devices

A list of promises can be empty. Say the Lindqvists go away for a week and switch every device off in the routine’s settings. If the code builds routine from the devices that are switched on, then the array is empty, and the routine still calls one of the four methods with it.

What does each method do with nothing to wait for? Save this as empty_routine.mjs. It gives each method the same empty array and logs what comes back. The call to Promise.race() has no await, and the output shows why:

Language: JavaScript Filename: empty_routine.mjs
const holiday = [];
const running = holiday.map((startDevice) => startDevice());

console.log("all():", await Promise.all(running));
console.log("allSettled():", await Promise.allSettled(running));
console.log("race():", Promise.race(running));

try {
  await Promise.any(running);
} catch (error) {
  console.log(`any(): ${error.name}`, error.errors);
}

Run it, and all four lines appear at once:

Language: Shell
$ node empty_routine.mjs
all(): []
allSettled(): []
race(): Promise { <pending> }
any(): AggregateError []

Promise.all() and Promise.allSettled() fulfill straight away with an empty array. There’s nothing to wait for and nothing that failed. Promise.any() rejects straight away with an AggregateError whose .errors array is empty, because no promise fulfilled.

Promise.race() is the odd one out. It settles the way the first promise to settle does. With no promises, its promise stays pending forever. An await on it would never finish.

In a script, Node.js would notice that nothing else can happen, stop, and print a warning that a top-level await never settled. If a routine can be empty, check running.length before you race it.

Check Your Understanding

Try these before you open the answers:

  1. Erik wants a message as soon as any one device works, and doesn’t care which. Which method fits? What does it reject with if every device fails, and where are the reasons?
  2. With the holiday routine empty, what does await Promise.allSettled(running) give back, and what does await Promise.race(running) do?
  3. Using routine and results from morning_report.mjs, write an expression that gives back the names of the devices that failed.
  1. Promise.any() fits. If every device fails, it rejects with an AggregateError, and the reasons are in its .errors array, in the order of the promises you passed in.
  2. Promise.allSettled() fulfills straight away with an empty array. Promise.race() never settles, so the await waits forever.
  3. Filter routine and use each device’s index to look up its result:
Language: JavaScript
routine
  .filter((startDevice, index) => {
    return results[index].status === "rejected";
  })
  .map((startDevice) => startDevice.name)

With the blinds offline, this gives back [ 'openBlinds' ]. Filtering results first wouldn’t work as well, because the filtered results lose their positions and you couldn’t match them to devices anymore.

To practice choosing between the four methods, click this button to ask the mentor for a quick quiz, one question at a time:

The next item is your first coding exercise in this course. It runs in your browser. You write your code in an editor on the page, then click Run Tests, and automated tests tell you what works and what doesn’t.

When a test fails, its message tells you what to change before you run the tests again. Full screen gives the editor more room. If you haven’t done a coding exercise on RealJS before, then the Contents tab below the editor explains how they work.

Next, in Exercise: Report the Morning’s Devices, you’ll write the Lindqvists’ morning report yourself, with stand-in devices that fail on purpose.

Become a Member to join the conversation.