April 6, 2023

TypeScript - Promise.all()

The Promise.all() method is one of the promise concurrency methods. It takes an interable of promises as input and returns a single promise object. It is useful for aggregating the result of multiple promises passed as input.

  • This returned promise fulfills when all of the input's promises fulfill/resolve.
  • It rejects immediately when any of the input's promises rejects.

It is typically used when there are multiple asynchronous tasks that we want to fulfill before the code execution continues.

In this example, since all the input promises are resolved, so the final promise will also get resolved.

const p1 = 10;
const p2 = Promise.resolve(20);
const p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
	resolve("value from promise3");
  }, 100);
});

Promise.all([p1, p2, p3]).then((values) => {
  console.log(values);
});

Output will be :

[ 10, 20, 'value from promise3' ]

Note that, the values parameter in .then() function will be an array containing all the output values from each input promise.

Lets see an example, if one of the promise from input is rejected.

// pass 4 promises: (1,2,3 and rejected-promise)
const p = Promise.all([1, 2, 3, Promise.reject(new Error("some error"))]);

p.then((values) => {
  //this will not get called.
  console.log(values);
})
.catch((error) => {
  //catch here for rejected promise
  console.error(error.message);
});

Output will be :

some error

Promise.all() executes the success callback when all the input promises are resolved. If any of the promise is rejected, then the rejection callback will be executed.

References:

Related Post(s):

1 comment: