Sobes.tech
Middle+

What is the difference between Promise.race and Promise.any?

sobes.tech AI

Answer from AI

Promise.race and Promise.any are methods for working with multiple promises, but they differ in logic:

  • Promise.race(promises) returns the result of the first promise that completes (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(promises) returns the result of the first successfully fulfilled promise. If all promises are rejected, then any is rejected 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' (the first settled promise)
  .catch(console.error);

Promise.any([p1, p2])
  .then(console.log) // Will output 'Success' (the first successfully fulfilled promise)
  .catch(console.error);
What is the difference between Promise.race and… - sobes.tech