Sobes.tech
Junior

What is Promise.all?

sobes.tech AI

Answer from AI

Promise.all is a static method of the Promise object that takes an iterable of promises (e.g., an array) and returns a new promise. This new promise resolves only when all promises in the iterable are resolved, or rejects immediately as soon as one promise is rejected.

  1. Resolution: If all promises are successfully resolved, the promise returned by Promise.all resolves with an array of the resolved values, maintaining the order of the original iterable.
  2. Rejection: If at least one promise is rejected, the promise returned by Promise.all is immediately rejected with the rejection reason of the first rejected promise. The remaining promises that are not yet settled will continue to execute, but their results will not be considered.

This is useful when you need to perform multiple asynchronous operations in parallel and wait for all of them to complete before proceeding with synchronous code.

// Example of using Promise.all
const promise1 = Promise.resolve(3);
const promise2 = 42; // Not a promise, but will be treated as a resolved promise with this value
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3])
  .then((values) => {
    console.log(values); // Outputs: [3, 42, 'foo']
  })
  .catch((error) => {
    console.error(error); // Will not be called in this example
  });

// Example with rejection
const promise4 = Promise.resolve('one');
const promise5 = Promise.reject('Error in promise 5');
const promise6 = Promise.resolve('three');

Promise.all([promise4, promise5, promise6])
  .then((values) => {
    console.log(values); // Will not be called
  })
  .catch((error) => {
    console.error(error); // Outputs: Error in promise 5
  });
What is Promise.all? — Node.js - sobes.tech