typestar

The four combinators in JavaScript

all, allSettled, race and any differ in what counts as finished.

const quick = (value, ms) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));
const failing = (ms) =>
  new Promise((_, reject) => setTimeout(() => reject(new Error("boom")), ms));

async function main() {
  console.log(await Promise.all([quick("a", 5), quick("b", 1)]));

  const settled = await Promise.allSettled([quick("ok", 1), failing(2)]);
  console.log(settled.map((r) => r.status));

  console.log(await Promise.race([quick("fast", 1), quick("slow", 20)]));
  console.log(await Promise.any([failing(1), quick("survivor", 5)]));

  try {
    await Promise.all([quick("a", 1), failing(2)]);
  } catch (error) {
    console.log("all rejected:", error.message);
  }
}

main();

How it works

  1. all rejects on the first failure; allSettled never rejects.
  2. race settles with whichever settles first, success or not.
  3. any waits for the first success, rejecting only if all fail.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
670
Tokens
235
Three-star pace
95 tpm

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

Type this snippet

Step 5 of 5 in Promises, step 5 of 19 in Promises & async.

← Previous Next →