Sobes.tech
Junior

What is Promise.all and how does it work?

sobes.tech AI

Answer from AI

Promise.all takes an iterable object (usually an array) of promises and returns a new promise.

How it works:

  • The returned promise resolves only when all input promises are successfully fulfilled. The result of the fulfilled promise will be an array of results from each input promise in the same order they were passed.
  • If at least one of the input promises is rejected, the returned promise immediately rejects with the reason of the first rejected promise.

Example:

// Array of promises
const promise1 = Promise.resolve(3);
const promise2 = 42; // Not a promise, will be treated as a resolved promise
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

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

Summary table:

All promises are fulfilled At least one promise is rejected
The resulting promise resolves with an array of results The resulting promise rejects with the reason of the first rejected promise

The main purpose of Promise.all is to perform multiple asynchronous operations in parallel and wait for all of them to complete.