Home > Web Front-end > JS Tutorial > body text

How is the Promise.any() method different from the Promise.race() method in JavaScript?

WBOY
Release: 2023-08-29 22:01:02
forward
973 people have browsed it

JavaScript 中的 Promise.any() 方法与 Promise.race() 方法有何不同?

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

The Promise.any() method in JavaScript is one of the Promise concurrent methods. It is useful when the first task needs to be completed.

The Promise.race() method in JavaScript is one of the Promise concurrency methods. It is useful when the first asynchronous task needs to complete but does not care about its final status (i.e. it can succeed or fail).

Example 1

In this example, let’s see how the Promise.any() 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.any method on all the three promise values")

Promise.any([promise1, promise2, promise3]).then((values) => console.log(values));
Copy after login

illustrate

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

  • Step 2 - Run the Promise.any() 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.race() method works

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

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

Promise.race([promise1, promise2, promise3]).then((values) => console.log(values));
Copy after login

illustrate

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

  • Step 2 - Run the Promise.race() 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.any() method different from the Promise.race() method in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!