Open In App

JavaScript Promise any() Method

Last Updated : 22 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript Promise any() method is a static method that takes an array of promises as a parameter and returns the first fulfilled promise. It returns a rejected value when all of the promises in the array return rejects or if the array is empty. When all the promises are rejected an AggregateError is returned which contains the reason for rejection.

Syntax:

Promise.any(iter)

Parameters: It takes only one parameter.

  • iter: It is iterable of promises.

Return Value: It returns a promise which is:

  • rejected if the parameter which is passed is empty
  • asynchronously fulfilled if the first fulfilled promise is encountered
  • asynchronously rejected if all the promises return a reject. In this case, an AggregateError is returned.

Example 1: This example, shows the basic use of Promise.any() method.

Javascript




let prom1 = new Promise((resolve, reject) => {
    reject("Failure");
})
let prom2 = new Promise((resolve, reject) => {
    reject("Failed to load");
})
let prom3 = new Promise((resolve, reject) => {
    resolve("Worked");
})
let prom4 = new Promise((resolve, reject) => {
    resolve("Successful");
})
 
let prom = [prom1, prom2, prom3, prom4];
 
Promise.any(prom).then((val) => { console.log(val) });


Output: The first two promises were rejected and the first successful promise which was prom3 was returned whose value is captured using then and printed on the console

Worked

Example 2: This example shows how the promise is rejected in any method.

Javascript




let prom1 = new Promise((resolve, reject) => {
    reject("Failure");
})
let prom2 = new Promise((resolve, reject) => {
    reject("Failed to load");
})
let prom3 = new Promise((resolve, reject) => {
    reject("Unsuccessful");
})
let prom4 = new Promise((resolve, reject) => {
    reject("Rejected");
})
 
let prom = [prom1, prom2, prom3, prom4];
 
Promise.any([])
    .then((val) => console.log(val))
    .catch(err => console.log(err));
Promise.any(prom)
    .then((val) => console.log(val))
    .catch(err => console.log(err));


Output: When we pass an empty array in any method it is automatically rejected and AggregateError is returned, also if all the promises passed in an array return a rejected same output is shown.

AggregateError: All promises were rejected
AggregateError: All promises were rejected

Supported Browsers: 

  • Google Chrome
  • Mozilla Firefox 
  • Opera 
  • Safari 
  • Edge 

We have a complete list of Javascript Promise methods, to check those please go through the Javascript Promise Reference article.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads