Sobes.tech
Middle

How does Promise.any differ from Promise.race?

sobes.tech AI

Answer from AI

Promise.any and Promise.race are similar in that both work with a set of promises, but they differ in logic:

  • Promise.race returns the result of the first promise that completes — whether successfully or with an error. That is, as soon as any of the promises is fulfilled or rejected, race will settle with that result.

  • Promise.any returns the result of the first successfully fulfilled promise. If all promises are rejected, then any rejects with an AggregateError.

Example:

const p1 = new Promise((_, reject) => setTimeout(() => reject('Error'), 100));
const p2 = new Promise(resolve => setTimeout(() => resolve('Success'), 200));

Promise.race([p1, p2])
  .then(console.log) // Will output 'Error' after 100ms
  .catch(console.error);

Promise.any([p1, p2])
  .then(console.log) // Will output 'Success' after 200ms
  .catch(console.error);

Thus, race reacts to the first settled promise, while any reacts to the first successful one.