typestar

Sequential or parallel in JavaScript

Two awaits in a row wait twice; starting both first does not.

const work = (name, ms) =>
  new Promise((resolve) => setTimeout(() => resolve(name), ms));

async function sequential() {
  const started = Date.now();
  await work("a", 20);
  await work("b", 20);
  return Date.now() - started;
}

async function parallel() {
  const started = Date.now();
  const [first, second] = await Promise.all([work("a", 20), work("b", 20)]);
  return [Date.now() - started, first, second];
}

async function main() {
  console.log("sequential ms >= 40:", (await sequential()) >= 39);
  const [elapsed] = await parallel();
  console.log("parallel ms < 40:", elapsed < 39);
}

main();

How it works

  1. await a(); await b(); is sequential, and often a bug.
  2. Start the promises, then await them together.
  3. The timing difference is the whole point of Promise.all.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
586
Tokens
179
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 107 seconds.

Type this snippet

Step 3 of 4 in async and await, step 8 of 19 in Promises & async.

← Previous Next →