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


We will learn about any() method of the promise in this tutorial. In JavaScript, we can use the promises to handle the asynchronous request. Writing the asynchronous code in our application to fetch the data makes it faster as it executes the other code without waiting for the data.

Promise.any() Method

As the name of any() method suggests, it will execute any promise fulfilled. So, whichever promise will resolve first, will be executed by the promise.any() method and others may or may not be executed. Also, all rejected promises were never executed by the promise.any() method.

Syntax

Users can follow the syntax below to use the promise.any() method.

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.

Parameters

  • Array_of_promise – It contains multiple promises, and whichever will be resolved quickly will be executed by the any() method.

Promise.any() with Async-await

The async and await keywords in JavaScript are used to work with asynchronous code. The async is used before a function definition to denote that the function is asynchronous and will return a promise. The await is used inside an async function to pause the execution until a specified promise is fulfilled.

Syntax

Following is the syntax for using the Promise.any() method with async-await in JavaScript:

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

Here, promise1, promise2, and so on are promises that you want to wait for. The Promise.any method returns a promise that is resolved with the value of the first input promise to be resolved, or rejected with an array of all input promises that have rejected if all input promises reject.

Example 1

In the example below, we have created the different promises using the Promise() constructor function. We have rejected the promise_2 and resolved the other promises, and we have resolved the promise_3 after the two milliseconds. So, promise_1 will execute successfully first.

In the output, we can observe that any() method prints the result of the promise_1 as 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 example below, we have created the async function getData(). Here, we have created the array of multiple promises and the promise using the fetch() method.

We are fetching the data from the real-time API. The request array contains the three promises, but in the output, we can observe that the result is not an iterable object and contains only the response from the promise resolved early.

<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 fulfilled by the first of three fetch Promises to be fulfilled. The function then uses the await keyword to wait for the Promise to be fulfilled and logs the response text. If any of the Promises is rejected, the catch block will be executed and will log the error to the console.

Using Promise.any() with async and await 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 to handle the first one that is fulfilled, while ignoring the others.

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

Updated on: 29-Dec-2022

614 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements