Loading article...
Promise.any() takes an iterable of promises and returns a single promise that resolves as soon as any of the input promises fulfills. If all promises reject, it rejects with an AggregateError containing all rejection reasons.
Promise.any returns a promise that:
Promise.resolve(...).then, resolve the outer promise.AggregateError , which contains all rejection reasons.AggregateErrorpromiseAnyfunction promiseAny(iterable) { return new Promise((resolve, reject) => { const promises = Array.from(iterable); const errors = []; let rejectedCount = 0; if (promises.length === 0) { return reject(new AggregateError([], "All promises were rejected")); } promises.forEach((p, i) => { Promise.resolve(p) .then(resolve) .catch((err) => { errors[i] = err; rejectedCount++; if (rejectedCount === promises.length) { reject(new AggregateError(errors, "All promises were rejected")); } }); }); }); }
promiseAny([ Promise.reject("fail1"), new Promise(res => setTimeout(() => res("success"), 100)), Promise.reject("fail2") ]).then(console.log) .catch(console.error); // β "success"
promiseAny([ Promise.reject("fail1"), Promise.reject("fail2") ]).then(console.log) .catch(err => { console.error(err instanceof AggregateError); // true console.error(err.errors); // ["fail1", "fail2"] });
Test your understanding with 3 quick questions