Explain Promise.any() with async-await in JavaScript
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...!!
Similar Reads
Explain Promise.all with async-await in JavaScript In JavaScript, Promise.all with async-await is used to handle multiple asynchronous operations concurrently. By combining Promise.all with await, you can wait for all promises to resolve or any to reject, ensuring that all asynchronous tasks are complete before proceeding with the next code executio
4 min read
Explain Promise.race() with async-await in JavaScript In this article, we will try to understand how we may implement Promise.race() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand how we may implement Promise.race() method. This method is one of the mos
3 min read
Explain Promise.allSettled() with async-await in JavaScript In this article, we will try to understand how we may implement the Promise.allSettled() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand about Promise.allSettled() method. This method is one of the mo
3 min read
Explain Async Await with Promises in Node.js Async/Await in Node.js is a powerful way to handle asynchronous operations. It allows you to write asynchronous code in a synchronous manner, making it easier to read, write, and debug. This feature is built on top of Promises, which represent a value that may be available now, or in the future, or
4 min read
How to delay a loop in JavaScript using async/await with Promise ? In JavaScript, you can delay a loop by using async/await with Promise. By wrapping a setTimeout() inside a Promise and using await, you can pause execution at each iteration, creating delays between loop iterations for asynchronous tasks without blocking the main thread.What is async and await?async
2 min read
How to use async/await with forEach loop in JavaScript ? Asynchronous is popular nowadays because it gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code. Async/await is used to write asynchronous code. In JavaScript, we use the looping technique to
2 min read
Async and Await in JavaScript Async and Await in JavaScript are used to simplify handling asynchronous operations using promises. By enabling asynchronous code to appear synchronous, they enhance code readability and make it easier to manage complex asynchronous flows.JavaScriptasync function fetchData() { const response = await
3 min read
How to use await outside of an async function in JavaScript ? In this article, we will try to understand in what way or by how we may use await outside of an async function in JavaScript with the help of both theoretical explanations as well as coding examples. Let us first understand the following shown section in which all the syntaxes of declaring a promise
4 min read
How to Implement a Custom Promise in JavaScript ? A custom Promise in JavaScript encapsulates asynchronous operations. It takes two parameters, resolves and rejects functions, and executes an async task. Resolve is called on success with the result, while reject is called on failure with an error. Table of Content Using Class SyntaxUsing Factory Fu
3 min read
How to use Async Await with Array.map in TypeScript ? In this article, we will learn how we can use async wait with Array.map() method in TypeScript. In TypeScript, the async and await are mainly used to work with asynchronous tasks. Using this we can write the code that consists of the tasks that take time to complete like reading the file, fetching d
3 min read