JS: Promise.any
(new in JS: ECMAScript 2021)
Promise.any(iterable)-
iterable is a Iterable Object. Each yield should be a promise. If not, it is treated as resolved value of fulfilled promise.
Returns a new promise that fulfills as soon as any of the input promises fulfills, using that fulfillment value. It rejects only if all input promise rejects.
Example. fulfilled
// Promise.any , example of fulfilled const xfail = new Promise((_, reject) => setTimeout(() => reject("xfail"), 50)); const slow = new Promise((resolve) => setTimeout(() => resolve("success"), 200)); const faster = new Promise((resolve) => setTimeout(() => resolve("first"), 100)); Promise.any([xfail, slow, faster]) .then( (x) => console.log("fulfilled with value:", x), (x) => console.log("rejected with value:", x), ); // fulfilled with value: first
Example. rejected
// Promise.any , reject example const xfail = new Promise((_, reject) => setTimeout(() => reject("fail"), 50)); const xbad = Promise.reject("bad"); Promise.any([xfail, xbad]) .then( (x) => console.log("fulfilled with value:", x), (x) => console.log("rejected with value:", x), ); /* rejected with value: [AggregateError: All promises were rejected] { [errors]: [ "fail1", "fail2" ] } */