Sikau

Advanced JavaScript · Day 19 · about 25 min

Promise combinators

all, allSettled, race and any.

Many promises at once

Loading a page might need the user, their courses and their badges — three requests. Waiting for each in turn wastes time. Promise.all and friends handle many promises together.

The four combinators

const wait = (ms, value, fail) =>
  new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));

async function main() {
  console.log(await Promise.all([wait(100, "user"), wait(50, "courses")]));

  const settled = await Promise.allSettled([wait(30, "ok"), wait(20, "broken", true)]);
  console.log(settled.map((r) => r.status));

  console.log(await Promise.race([wait(80, "slow"), wait(10, "fast")]));
  console.log(await Promise.any([wait(10, "x", true), wait(40, "backup")]));
}
main();

The rest of this lesson

  • Parallel versus sequentialexplain
  • Choosing the right combinatorexplain
  • Predictpredict
  • Which combinator?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript