Start Every Device at Once

Erik and Saga want one tap on Good morning to start the lights, the kettle, the blinds, and the heating. Most people first write code that starts one device after another. Then the morning drags because the kettle sits cold while the lights take their turn.

In this lesson, you’ll start every device at once and then wait for all of them together. You’ll see that calling an async function starts its work right away and that Promise.all() only waits for work that’s already running. You’ll type each script along with the lesson and run it in your terminal. Start with a single device and a single await.

Wait for One Device

Before the routine can start four devices, it needs devices to start. They’re stand-ins, so you need no hardware, and each device returns the same status on every run.

Open your terminal, make a folder for the course’s scripts, and move into it:

Language: Shell
$ mkdir morning
$ cd morning

In your editor, save this file in the morning folder as devices.mjs. It’s a module that exports one async function per device:

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);
  return "Blinds open";
}

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

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

The first line imports Node.js’s promise-based version of setTimeout(), renamed delay(). It returns a promise that fulfills once about the specified number of milliseconds has passed, usually a moment later. So each device waits for its own delay and then returns its status line. The lights are the quickest, and the kettle is the slowest by far.

Now save the routine’s first version as good_morning.mjs. It turns on the lights and logs what they report:

Language: JavaScript Filename: good_morning.mjs
import { turnOnLights } from "./devices.mjs";

const lights = await turnOnLights();
console.log(lights);

Run it, and after a moment, the lights report back:

Language: Shell
$ node good_morning.mjs
Lights on

The await pauses the script until the lights’ promise fulfills, then hands you its value. The .mjs extension makes the file an ES module, short for ECMAScript module. That’s why await works at the top level here.

Start Every Device Before You Wait

With one device working, the natural next step is to add three more lines like the first. That version reads well, but it has a cost:

Language: JavaScript
const lights = await turnOnLights();
const kettle = await boilKettle();
const blinds = await openBlinds();
const heating = await warmUpHeating();

Each await pauses the script until that device has finished. So boilKettle() isn’t even called until the lights are on, and the blinds wait for the kettle. The devices don’t depend on each other, so there’s no reason for any of them to wait its turn.

You already know that calling an async function starts its work straight away and gives you a promise for its result. The await doesn’t start anything. It only waits. So you can call all four first and wait afterward.

Replace good_morning.mjs with a version that lists the routine’s devices and starts each one:

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

const routine = [turnOnLights, boilKettle, openBlinds, warmUpHeating];
const running = routine.map((startDevice) => startDevice());
console.log(running);

The routine array holds the four functions themselves, not calls to them. The .map() callback calls each one as startDevice(), and .map() collects what each call returns. Run the script:

Language: Shell
$ node good_morning.mjs
[
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> }
]

The array prints at once, and it holds four promises, all still pending. All four devices have started, and their waits now overlap. Your code still runs on one thread, executing one JavaScript operation at a time. The .map() call runs each device’s function up to its await, gets back a pending promise, and then moves on to the next. So the kettle’s wait doesn’t queue behind the lights’.

Nothing waits for the devices yet, so their results go nowhere. Node.js still keeps the script alive until the last device finishes, which is why your prompt doesn’t come back straight away.

If you’d like to check your understanding of what a call starts and what an await does, then click this button to ask the mentor, with the script above attached:

Wait for Them All With Promise.all()

The devices are running, but the routine still needs their statuses. That’s the job of Promise.all(). You give it an array of promises, and it gives you back one promise. That promise fulfills with an array of their values once every promise in the input array has fulfilled.

Replace the console.log() line at the end of good_morning.mjs with an await on Promise.all():

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

const routine = [turnOnLights, boilKettle, openBlinds, warmUpHeating];
const running = routine.map((startDevice) => startDevice());
const statuses = await Promise.all(running);
console.log(statuses);

Before you run it, make a prediction. The lights finish first, and the kettle finishes last, but the kettle is second in routine. In what order will the four statuses appear? Run node good_morning.mjs, then open the box to compare.

After the kettle has boiled, the whole array appears at once:

Language: Shell
$ node good_morning.mjs
[ 'Lights on', 'Kettle boiled', 'Blinds open', 'Heating on' ]

The statuses come back in the order you listed the devices, not the order they finished. Promise.all() puts each value at the same position as its promise in the array you passed in. So statuses[1] always belongs to routine[1], the kettle, however long the kettle takes.

The routine keeps this shape for the rest of the course. It starts the work with .map(), then waits for it with Promise.all(). Here, every device works, so Promise.all() fulfills. When one device fails, Promise.all() stops waiting, but that doesn’t stop the other devices, which keep running to the end.

Check Your Understanding

Try these before you open the answers:

  1. In the final good_morning.mjs, which line starts the devices, and which line waits for them? Explain why the blinds don’t have to wait for the kettle before they start.
  2. Erik deletes the await in front of Promise.all(). Does removing await prevent any device from starting? Explain why or why not.
  3. On weekdays, Erik only wants the kettle and the heating. Write the two statements that start both and wait for their statuses.
  1. The routine.map() line starts the devices: its callback calls each function, and each call starts that device’s work and hands back a promise. The await Promise.all(running) line only waits. By the time it’s reached, all four devices have started, so the blinds’ wait is never queued behind the kettle’s.
  2. No. The .map() call still starts all four devices before the script reaches Promise.all(). Without await, the script doesn’t pause, so statuses holds the promise from Promise.all() instead of the devices’ status lines.
  3. List the two devices, start them with .map(), and await Promise.all():
Language: JavaScript
const weekday = [boilKettle, warmUpHeating];
const statuses = await Promise.all(
  weekday.map((startDevice) => startDevice()),
);

The statuses come back as [ 'Kettle boiled', 'Heating on' ].

To practice the start-then-wait shape on routines of your own, click this button for a quick quiz:

Starting every device before waiting must save the Lindqvists some time in the morning. But how much time did that save? You’ll find out later in the course, in the section One at a Time or All Together.

For now, the routine works, and the statuses come back in the order you listed the devices. But the Lindqvists’ blinds don’t always answer. Next, in Watch Four Promises Settle, the blinds go offline, and you’ll watch Promise.all() and three related methods settle when one device fails.

Become a Member to join the conversation.