Junior — Middle
How is the simultaneous execution of multiple promises achieved using Promise.all and how are their results processed?
sobes.tech AI
Answer from AI
Promise.all allows you to run multiple promises in parallel and wait for all of them to complete. It takes an array of promises and returns a new promise that:
- Resolves successfully if all promises in the array are fulfilled. The result will be an array of values corresponding to each promise in the same order.
- Rejects if at least one promise is rejected, and returns the error of the first rejected promise.
Example usage:
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);
Promise.all([promise1, promise2, promise3])
.then(results => {
console.log(results); // [1, 2, 3]
})
.catch(error => {
console.error('One of the promises was rejected:', error);
});
Thus, Promise.all is useful for executing multiple asynchronous operations simultaneously and handling their results after all have completed.