Home  >  Article  >  Web Front-end  >  Explain Promise.any() and async-await in JavaScript?

Explain Promise.any() and async-await in JavaScript?

PHPz
PHPzforward
2023-09-13 22:17:021051browse

在 JavaScript 中解释 Promise.any() 和 async-await ?

We will learn about the any() method of Promise in this tutorial. In JavaScript, we can use Promise to handle asynchronous requests. Writing asynchronous code in our application to get the data speeds things up because it doesn't have to wait for the data to execute other code.

Promise.any() method

As the name of the any() method indicates, it will execute any fulfilled promise. Therefore, whichever Promise resolves first will be executed by the Promise.any() method, while other Promises may or may not be executed. Additionally, any rejected Promise will not be executed by the Promise.any() method.

Syntax

Users can use the promise.any() method according to the following syntax.

Promise.any(Array_of_promise).then(
   // handle result
)

In the above syntax, we can handle the result returned by any Promise in the "then" block.

parameter

  • Array_of_promise – It contains multiple Promises, the ones that can be resolved quickly will be executed by the any() method.

Promise.any() with asynchronous wait

The async and await keywords in JavaScript are used to handle asynchronous code. async is used before a function definition to indicate that the function is asynchronous and will return a Promise. wait is used inside an asynchronous function to pause execution until a specified Promise is met.

grammar

The following is the syntax for using the Promise.any() method and async-await in JavaScript:

async function example() {
   try {
      const result = await Promise.any([promise1, promise2, ...]);
   } catch (error) {
      // handle error
   }
}

Here, promise1, promise2, etc. are the promises you want to wait for. The Promise.any method returns a Promise that is resolved using the value of the first input Promise to be resolved, or, if all input Promise are rejected, an array of all input Promise that were rejected.

Example 1

In the following example, we create different Promises using the Promise() constructor. We reject promise_2 and resolve the other promises, and we resolve promise_3 two milliseconds later. Therefore, promise_1 will execute successfully first.

In the output, we can observe that the any() method prints the result of promise_1 because it will be resolved early.

<html>
<body>
   <h2> Using the Promise.any() Method </h2>
   <div id="output"> </div>
   <script>
      let promise_1 = new Promise((res, rej) => {
         res("Resolved promise with time of 0 milliseconds");
      });
      let promise_2 = new Promise((res, rej) =>
      rej("This promise is rejected!")
      );
      let promise_3 = new Promise((res, rej) => {
         setTimeout(() => {
            res("Resolved promise with time of 2000 milliseconds");
         }, 2000);
      });
      // resolving the promises
      Promise.any([promise_1, promise_2, promise_3]).then((response) => {
         document.getElementById("output").innerHTML += response;
      });
   </script>
</body>
</html>

Example 2

In the following example, we create the asynchronous function getData(). Here, we use the fetch() method to create multiple Promise arrays and Promises.

We are getting data from real time API. The requests array contains three Promises, but in the output we can observe that the result is not an iterable object and contains only the responses of earlier resolved Promises.

<html>
<body>
   <h2>Using Promise.any() with async-await </h2>
   <button onclick="getData()"> Fetch any one promise Data </button>
   <div id="output"> </div>
   <script>
      async function getData() {
         try {
            // multiple promises
            const requests = [
               fetch("https://jsonplaceholder.typicode.com/todos/1"),
               fetch("https://jsonplaceholder.typicode.com/todos/2"),
               fetch("https://jsonplaceholder.typicode.com/todos/3"),
            ];
            const result = await Promise.any(requests);
            document.getElementById("output").innerHTML =
            "The status of result is " + result.status;
         } 
         catch (error) {
            document.getElementById("output").innerHTML = error;
         }
      }
   </script>
</body>
</html>

In this example, the getData function uses Promise.any() to create a Promise that is implemented by the first of three fetch Promise to be implemented. The function then uses the await keyword to wait for the Promise to be fulfilled and log the response text. If any Promise is rejected, the catch block will be executed and an error will be logged to the console.

Using Promise.any() with async and wait can be a useful way to handle multiple Promises in a concise and readable way. It allows you to specify a set of Promises and handle the first fulfilled Promise while ignoring the others.

We learned how to use the any() Promise method in this tutorial. The goal of using the any() method is to execute the only method in the resolved Promise.

The above is the detailed content of Explain Promise.any() and async-await 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