Middle
What is the difference between Promise.all and Promise.any?
sobes.tech AI
Answer from AI
Promise.all waits for the completion of all promises in an iterable object. If all promises are fulfilled successfully, it returns a promise that resolves with an array of results in the same order as the input promises. If at least one promise is rejected, it returns a promise that rejects with the error of the first rejected promise.
Promise.any waits for any of the promises in an iterable object to fulfill. As soon as any promise is fulfilled successfully, it returns a promise that resolves with the value of that promise. If all promises are rejected, it returns a promise that rejects with an AggregateError, containing an array of errors from all rejected promises.
Comparison:
| Criterion | Promise.all | Promise.any |
|---|---|---|
| Success condition | All promises fulfilled successfully | Any promise fulfilled successfully |
| Error condition | Any promise is rejected | All promises are rejected |
| Success result | Array of results (in the same order as input promises) | Value of the first successfully fulfilled promise |
| Error result | Error of the first rejected promise | AggregateError with an array of errors from all rejected promises |
| Usage | Dependence on all asynchronous operations | Dependence on any of the asynchronous operations |