English English

Warning: count(): Parameter must be an array or an object that implements Countable in /var/www/ard-site/templates/ardsite/library/Designer/Content/SingleArticle.php on line 198

[ECMAScript 2021] - The Promise.any() function explained

This function is part of promises, which allow asynchronous programming. This function "Promise.any()" is used to return the value of promise as soon as one of the used promises are resolved.

"Promise.any()" was introduced in the ECMAScript 2021. It works in: Chrome and Edge version 85+ (and newer), Firefox version 79+ and Safari 14+. 

Promise.any([promise1, promise2]).

This function takes one or more promises as arguments. It returns the value of the first resolved promise.


This function used in an example:

const promiseObj1 = Promise.reject(0);
const promiseObj2 = new Promise((res) => setTimeout(res, 1000, "Promise Number 2"));
const promiseObj3 = new Promise((res) => setTimeout(res, 200, "Promise Number 3"));
const promiseObj4 = new Promise((res) => setTimeout(res, 400, "Promise Number 4"));


Promise.any([promiseObj1, promiseObj2, promiseObj3, promiseObj4]).then((val) => alert(val));

This function has 4 promises (promiseObj1, promiseObj2, promiseObj3 and promiseObj4). The last 3 wait for some seconds before they return their name.
When the first promise is resolved, then its value is displayed in an alert popup.

 

More information about promises:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any

We use cookies on our website. They are essential for the operation of the site
Ok