Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 26 Apr, 2022

In this article, we will try to understand how to implement the Promise.any() method with async-await in JavaScript using some theoretical explanations followed by some coding examples as well.

Let us firstly quickly understand the working of Promise.any() method with some theoretical examples (including the syntax of declaring this particular method) followed by a short example for better conceptual understanding.

Working of Promise.any() method:

  • Promise.any() method is one of the most commonly used Promise object’s methods in which if any promise which is successfully fulfilled (that is not in the rejected state) will be executed by this particular method.
  • The one which is in the rejected state will be rejected and won’t be executed by this method. 
  • Suppose there are four promises in line and three of them are successfully fulfilled (that is “resolved”) and one of them is rejected, then out of these three promises, the one which is quicker will be executed first and the rest remaining ones may not be executed by this method.
  • Promise.any() method somehow behaves in a similar manner as Promise.race() method behaves, as in Promise.race() method, whichever promise gets successfully fulfilled (or resolved) first, that only promise will be executed and the rest ones remain unexecuted.

Syntax of Promise.any() method: Following is the syntax which we may use to implement Promise.any() method:-

Promise.any([first_promise , second_promise , ...]).then(
    // do something.....
)

Now that we have seen some theoretical explanations of Promise.any() method let us now quickly visualize all of the above-illustrated facts using an example which is as follows:-

Example 1: In this example, we will be creating four promises, one will be in the rejected state and the other three will be in the resolved state. Inside all the resolved promises, we will be creating separate timer functions (setTimeout functions) with different timers each. Then we will be using the Promise.any() method which will accept an iterable object (in most cases an array could be preferred or used) consisting of different promises at one time. Afterward using the then() method, we will try to output the result obtained after the execution of promises using this method over the browser’s console.

Javascript




<script>
    let rejected_promise = new Promise(
        (resolve, reject) => reject("Rejected Promise...."));
  
    let first_resolved_promise = new Promise(
        (resolve, reject) => {
            setTimeout(() => {
                resolve("GeeksforGeeks...!!");
            }, 1000);
        });
  
    let second_resolved_promise = new Promise(
        (resolve, reject) => {
            setTimeout(() => {
                resolve("JavaScript......!!");
            }, 2000);
        });
  
    let third_resolved_promise = new Promise(
        (resolve, reject) => {
            setTimeout(() => {
                resolve("TypeScript...!!");
            }, 3000);
        });
  
    let combined_promise = [
        rejected_promise,
        first_resolved_promise,
        second_resolved_promise,
        third_resolved_promise,
    ];
  
    Promise.any(combined_promise)
        .then((result) => console.log(result));
</script>


Output:

GeeksforGeeks...!!

Now that we have understood Promise.any() method with an example too. Let us now see how we may implement Promise.any() method with async-await keywords using the following illustrated example:

Example 2: In this example, we will be creating four promises, as we have created in the previous example in the same manner. Then we will implement a method in which we will add async keyword in prefix which would indicate that this particular function is now able to handle all the asynchronous requests that are coming to it. Afterward, we will create an iterable object (an array) consisting of all the four promises inside it and we will fetch the data (the array) inside another variable using another keyword called await which will wait until the data is completed fetched inside that asynchronously response accepting function. Thereafter using the Promise.any() method we will output the result over the browser’s console using then() and console.log() methods.

Javascript




<script>
    let rejected_promise = new Promise(
        (resolve, reject) => reject("Rejected Promise...."));
  
    let first_resolved_promise = new Promise(
        (resolve, reject) => {
            setTimeout(() => {
                resolve("GeeksforGeeks...!!");
            }, 1000);
        });
  
    let second_resolved_promise = new Promise(
        (resolve, reject) => {
            setTimeout(() => {
                resolve("JavaScript......!!");
            }, 2000);
        });
  
    let third_resolved_promise = new Promise(
        (resolve, reject) => {
            setTimeout(() => {
                resolve("TypeScript...!!");
            }, 3000);
        });
  
    let combined_promise = [
        rejected_promise,
        first_resolved_promise,
        second_resolved_promise,
        third_resolved_promise,
    ];
  
    async function displayResult() {
        try {
            let promise_array = [
                rejected_promise,
                first_resolved_promise,
                second_resolved_promise,
                third_resolved_promise,
            ];
            let result = await promise_array;
              
            Promise.any(combined_promise)
                .then((result) => console.log(result));
        } catch (error) {
            console.log(error.message);
        }
    }
  
    displayResult();
</script>


Output:

GeeksforGeeks...!!

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!