Junior — Middle
Can you explain how Promise.all works and what it is used for?
sobes.tech AI
Answer from AI
Promise.all takes an array (or iterable) of promises and returns a new promise that:
- Resolves successfully when all the input promises are fulfilled. The result is an array of all the promise values in the same order.
- Rejects if any of the promises is rejected, and returns the reason of the first rejected promise.
This is useful when you want to perform multiple asynchronous operations in parallel and wait for all of them.
Example:
const p1 = Promise.resolve(1);
const p2 = new Promise(resolve => setTimeout(() => resolve(2), 100));
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3])
.then(results => {
console.log(results); // [1, 2, 3]
})
.catch(error => {
console.error('One of the promises rejected:', error);
});