Each time a promise contained within the iterable object, resembling an array, is successfully fulfilled or resolved, the function yields a promise that either resolves or rejects.
A promise. Among the various methods associated with promises in concurrency, one notable method is any. This method is useful as it returns the first promise that fulfills successfully. Once a promise is resolved, it effectively short-circuits, eliminating the need to wait for the remaining promises to complete.
The Promise.Any method resolves as soon as at least one of the promises provided is fulfilled. Conversely, it rejects with an AggregateError if every single promise in the input remains unfulfilled.
Syntax
The syntax presented below illustrates the utilization of the Promise.any method, which accepts an array of promise arguments as input.
Promise.any(promise1, promise2… ,promises);
Explanation: The method Promise.any returns a singular promise that resolves to the result of the first promise that is successfully fulfilled from a given array of promises.
Return Value: This method yields the following values:
If the provided argument is null or undefined, a fulfilled Promise is returned.
The values and specific statuses of each promise passed into it are included in a pending promise created in all other cases.
- Status and value are the two attributes that each object
- The status is either accepted or fulfilled.
- The benefit if the promise is kept or the justification if it is rejected.
- One of the most popular methods on the Promise object is any, which is used to execute any promise that has been successfully fulfilled and is not currently in the rejected state.
- This method will reject and prevent the execution of the one in the rejected state.
- The promise that can be fulfilled the fastest will be carried out first, and the subsequent promises may not be carried out using this approach if there are four promises in line and three of them are successfully carried out (that is, "resolved") and one of them is refused.
- Somehow, the Promise.any method behaves similarly to Promise.
- With the race method, only the successfully fulfilled promise will be executed first; the other promises will not be.
Working procedure of the promise.any method
Diagrams
Input argument Diagram
The functionality of the Promise.any method, specifically when all promises are resolved, is illustrated in the diagram provided below:
- At time t1, the promise1 resolves to the value v1.
- At time t2, the promise2 resolves to the value v2.
- The Promise.any function delivers a promise that, at time t1, resolves to the value v1.
Even in cases where a portion of the promises contained within the iterable object are rejected, the any method returns a promise that resolves as soon as the first promise is fulfilled:
Input argument Diagram
The operation of the Promise.any method, where one promise is rejected while the others are resolved, is illustrated in the diagram below:
- Promise1 is declined with a mistake at time point 1.
- The promise2 to value v2 at t2 is kept.
- A promise that resolves to a value v2-the outcome of the promise2-is returned by the Promise.any method.
It is important to note that the Promise.any method ignores any rejected promises (e.g., promise1).
- any produces a promise that rejects with an AggregateError, which encapsulates all the reasons for rejection.
- This occurs when every promise within the iterable object is rejected or when the IEnumerable object lacks any entries. AggregateError is a subclass of Error.
Input argument Diagram
The operation of the Promise.any method when all promises are rejected is illustrated in the diagram below:
An error occurring at time1 results in the rejection of promise1.
Promise2 is rejected at time two as a result of error2.
The AggregateError produced by the Promise.any function encompasses both error1 and error2 from all promises that encountered rejection, in addition to a promise that faced rejection at the moment t2.
Examples of JavaScript Promise.any method
The provided examples illustrate the use of any with an array of input Promises. It is possible to generate several promises that can either be fulfilled or rejected, or a combination of both fulfilled and rejected.
Example 1:
The fundamental Promise.any method in JavaScript is utilized for retrieving results and values based on a given input argument. By employing this method, it is possible to obtain the result status along with an undefined value over a specified duration.
<!DOCTYPE html>
<html>
<head>
<title> JavaScript's Promise.any() method </title>
<script>
console.log("JavaScript's Promise.any() method");
const pr1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('first Promise is fulfilled');
resolve(1);
}, 1000);
});
const pr2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(' second Promise is fulfilled');
resolve(2);
}, 2000);
});
const pr3 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(' last Promise is fulfilled');
resolve(3);
}, 3000);
});
const pr = Promise.any([pr1, pr2, pr3]);
pr.then((value) => {
console.log('Returned Promises with');
console.log(value);
});
</script>
</head>
<body>
<h3> JavaScript's Promise.any() method </h3>
</body>
</html>
Output
The illustration displays all the resolved outcomes of the promise.any function.
Example 2:
The illustration demonstrates the use of promises, featuring one that is rejected and another that is resolved, utilizing the promise method. In this instance, we are working with several promises that are executed over a specified duration for the operation.
<!DOCTYPE html>
<html>
<head>
<title> JavaScript's Promise.any() method </title>
<script>
console.log("JavaScript's Promise.any() method");
const pr1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(' first Promise is rejected');
reject('error');
}, 1000);
});
const pr2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(' second Promise is fulfilled');
resolve(2);
}, 2000);
});
const pr = Promise.any([pr1, pr2]);
pr.then((value) => {
console.log('Returned Promises with');
console.log(value);
});
</script>
</head>
<body>
<h3> JavaScript's Promise.any() method </h3>
</body>
</html>
Output
The illustration depicts one value that was rejected and another that was successfully resolved from the promise.any method.
Example 3:
The following example illustrates promises that are all in a rejected state by utilizing the promise method. In this instance, we implement several promises, each with the necessary duration for the intended functionality.
<!DOCTYPE html>
<html>
<head>
<title> JavaScript's Promise.any() method </title>
<script>
console.log("JavaScript's Promise.any() method");
const pr1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(' first Promise is rejected');
reject('error');
}, 1000);
});
const pr2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(' second Promise is fulfilled');
reject('error1');
}, 2000);
});
const pr3 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(' third Promise is fulfilled');
reject('error3');
}, 1000);
});
const pr = Promise.any([pr1, pr2, pr3]);
pr.catch((value) => {
console.log('Returned Promises with rejected message');
console.log(value, value.error);
});
</script>
</head>
<body>
<h3> JavaScript's Promise.any() method </h3>
</body>
</html>
Output
The illustration displays all the values that were rejected by the promise.any function.
Example 4:
The promise.any function employs the then, catch, and finally constructs to complete its operations and present results. It allows for the utilization of all these methods, even when dealing with an empty iterable value in promise.any. The finally method invokes the input data and subsequently outputs it for display.
<!DOCTYPE html>
<html>
<head>
<title> JavaScript's Promise.any() method </title>
<script>
console.log("JavaScript's Promise.any() method");
Promise.any([])
.then((values) => console.log(values))
.catch((err) => console.log(err))
.finally(() => console.log("Operations of the Promise.any() have completed."));
</script>
</head>
<body>
<h3> JavaScript's Promise.any() method </h3>
</body>
</html>
Output
The console tab presents the output alongside comprehensive information.
When to utilize the Promise.any method in JavaScript
To implement the initial fulfilled promise in practice, you can utilize the Promise.any method. This function does not wait for all promises to be resolved. In other terms, as soon as one promise is resolved, the Promise.any method exits early.
It is possible that you possess a resource utilized by multiple networks that distribute content, such as a Content Delivery Network (CDN). The Promise.any method serves to dynamically load the first resource that becomes available.
Example
The following illustration demonstrates how to obtain two images utilizing the Promise.any function, subsequently displaying the first one that becomes accessible.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "UTF-8" />
<meta name = "viewport" content="width=device-width, initial-scale=1.0" />
<title> JavaScript Promise.any() Demo </title>
</head>
<body>
<script>
function getImageData(url) {
return fetch(url).then((response) => {
if (!response.ok) {
throw new Error(`HTTP output status: ${response.status}`);
}
return response.blob();
});
}
let image1 = getImageData(
'https://upload.wikimedia.org/wikipedia/commons/4/43/Siberian_black_tabby_blotched_cat_03.jpg'
);
let image2 = getImageData(
'https://upload.wikimedia.org/wikipedia/commons/a/af/Golden_retriever_eating_pigs_foot.jpg'
);
Promise.any([image1, image2])
.then((data) => {
let objectURLinfo = URL.createObjectURL(data);
let images = document.createElement('img');
images.src = objectURLinfo;
document.body.appendChild(images);
})
.catch((e) => {
console.log(e.message);
});
</script>
</body>
</html>
Output
The result displays one image as resolved promise data and another image as rejected.
How it operates
- First, create the getImageBlob function, which fetches the image's blob from a URL using the retrieve API. The promise object that the getImageBlob method returns resolves to the image blob.
- Make two promises that fetch the images second.
- Third, employ the Promise.any method to display the first image that becomes available.
Conclusion
To identify the first promise that resolves from a collection, utilize the JavaScript method Promise.any.