How does Promise.all() method differs from Promise.allSettled() method in JavaScript?


In this article, you will understand how does Promise.all() method differs from the Promise.allSettled() method in JavaScript.

The Promise.all() method takes in one or multiple promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises are fulfilled. It rejects a promise when any of the input's promises is rejected, with this first rejection reason.

The Promise.allSettled() method takes in one or multiple promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.

Example 1

In this example, let’s look at how the Promise.all method works.

console.log("Defining three promise values: promise1, promise2 and promise3");
const promise1 = Promise.resolve(1);
const promise2 = new Promise((resolve, reject) => {
   setTimeout(resolve, 2 , 'Promise Two');
});
const promise3 = 3;

console.log("Running Promise.all method on all the three promise values")

Promise.all([promise1, promise2, promise3]).then((values) => console.log(values));

Explanation

  • Step 1 −Define three promise values namely promise1, promise2, promise3 and add values to them.

  • Step 2 −Run Promise.all() method on all the promise values.

  • Step 3 −Display the promise values as result.

Example 2

In this example, let’s look at how the Promise.allSettled method works

console.log("Defining three promise values: promise1, promise2 and promise3");
const promise1 = Promise.resolve(1);
const promise2 = new Promise((resolve, reject) => {
   setTimeout(resolve, 2 , 'Promise Two');
});
const promise3 = 3;

console.log("Running Promise.allSettled method on all the three promise values")

Promise.allSettled([promise1, promise2, promise3]).then((values) => console.log(values));

Explanation

  • Step 1 −Define three promise values namely promise1, promise2, promise3 and add values to them.

  • Step 2 −Run Promise.allSettled() method on all the promise values.

  • Step 3 −Display the promise values as result.

Updated on: 16-Feb-2023

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements