CodePark/ questions / Promises & async/await
START PRACTICINGPRACTICE
Frontend question · JavaScript › Promises & async/await

What does this log?

const slowOk = new Promise((res) => setTimeout(() => res("slow ok"), 100));
const fastFail = new Promise((_, rej) =>
  setTimeout(() => rej(new Error("fast fail")), 10)
);

Promise.race([slowOk, fastFail]).then(
  (v) => console.log("race:", v),
  (e) => console.log("race:", e.message)
);
Promise.any([slowOk, fastFail]).then((v) => console.log("any:", v));
race: fast fail, then any: slow ok

The answer is "race: fast fail, then any: slow ok". race settles with whichever promise settles first, even a rejection. fastFail rejects after 10 ms, so race reports fast fail. any ignores rejections and waits for the first success, which is slow ok.

The tempting option "race: fast fail, then an AggregateError from any" is wrong.
any rejects with an AggregateError only if every promise rejects, and slowOk fulfills.