English English

[ECMAScript 2021] - La fonction Promise.any() expliquée

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. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.

Ok