Junior — Middle
What is the difference between Promise.all and Promise.any when handling promises?
sobes.tech AI
Answer from AI
Promise.all takes an array of promises and returns a new promise that:
- resolves when all promises in the array are successfully completed, returning an array of results in the same order;
- rejects if at least one of the promises is rejected, immediately with that promise's error.
Promise.any takes an array of promises and returns a promise that:
- resolves as soon as any one of the promises successfully completes, returning that promise's result;
- rejects if all promises are rejected, returning an AggregateError with the errors of all promises.
Example:
const p1 = Promise.reject('Error 1');
const p2 = Promise.resolve('Success 2');
const p3 = Promise.resolve('Success 3');
Promise.all([p1, p2, p3])
.then(console.log) // will not be called
.catch(console.error); // will output 'Error 1'
Promise.any([p1, p2, p3])
.then(console.log) // will output 'Success 2'
.catch(console.error);