Home  >  Article  >  Web Front-end  >  How is the Promise.all() method different from the Promise.allSettled() method in JavaScript?

How is the Promise.all() method different from the Promise.allSettled() method in JavaScript?

WBOY
WBOYforward
2023-08-25 11:45:05823browse

JavaScript 中的 Promise.all() 方法与 Promise.allSettled() 方法有何不同?

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

The Promise.all() method accepts one or more Promise as input and returns a Promise. When all input promises have been fulfilled, the returned promises are fulfilled. When any input promise is rejected, it rejects the promise and gives the first rejection reason.

The Promise.allSettled() method accepts one or more Promise as input and returns a Promise. When all input promises resolve (including when passing an empty iterable object), the returned promises are fulfilled, with an array of objects describing the results of each promise.

Example 1

In this example, let's see 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));

illustrate

  • Step 1 - Define three Promise values, Promise1, Promise2, Promise3 and add values ​​to them.

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

  • Step 3 - Display the promise value as the result.

Example 2

In this example, let’s see 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));

illustrate

  • Step 1 - Define three Promise values, Promise1, Promise2, Promise3 and add values ​​to them.

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

  • Step 3 - Display the promise value as the result.

The above is the detailed content of How is the Promise.all() method different from the Promise.allSettled() method in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete