In the last lesson, you timed the routine both ways and found that only the steps that need an earlier result have to run in sequence. The four devices don’t need each other, so they should start together.
Starting them together is only half of what Erik needs, though. He wants the routine to collect every device’s status and then announce that it’s done, so your code has to know when all four have finished. In this lesson, you’ll make the routine wait for every device and hear about the one that fails, so its “done” means done. Start with the loop that looks like the shortest way to do it.
Start Every Device With .forEach()
Erik wants the routine to log each device’s status as soon as it arrives, collect the statuses in an array for the morning report, and then say that it’s done.
Calling a function for every device in a list is what .forEach() is for, and you’ve used it plenty of times.
You may remember trying .forEach() with an async callback when the goal was to run jobs one after another, and it started them all at once instead. This time, that’s the goal. So .forEach() looks like a good fit. It takes less code than .map(), and you have no promises to keep track of.
The blinds are offline again this morning. Work in your morning folder and make sure your devices.mjs is the version where openBlinds() throws after two seconds:
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 save the routine as wait_routine.mjs. The callback awaits each device, logs its status, and pushes it into statuses. A timer measures how long the whole routine takes:
wait_routine.mjs
import {
turnOnLights,
boilKettle,
openBlinds,
warmUpHeating,
} from "./devices.mjs";
const routine = [turnOnLights, boilKettle, openBlinds, warmUpHeating];
const statuses = [];
console.time("routine");
routine.forEach(async (startDevice) => {
const status = await startDevice();
console.log(status);
statuses.push(status);
});
console.timeEnd("routine");
console.log("Routine done:", statuses);
Before you run node wait_routine.mjs, predict what the timer reads, what Routine done: shows, and what happens when the blinds fail.