Sobes.tech
Middle

How does the Promise.all method work in JavaScript?

sobes.tech AI

Answer from AI

Promise.all accepts an iterable object (e.g., an array) of promises and returns a new promise.

This new promise:

  • Resolves if all promises in the passed iterable object successfully resolve. The value is an array of results of all promises in the order they were passed.
  • Rejects as soon as one of the promises in the passed iterable object rejects. The value is the reason for the rejection of the first rejected promise.
  • If the passed iterable object is empty, the returned promise immediately resolves with an empty array.

Example:

const promise1 = Promise.resolve(3);
const promise2 = 42; // Not a promise, will be wrapped in a promise
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);
  });

Example with error:

const promise4 = Promise.resolve('success');
const promise5 = Promise.reject('error');

Promise.all([promise4, promise5])
  .then((values) => {
    console.log(values); // Will not execute
  })
  .catch((error) => {
    console.error(error); // Outputs: error
  });