Overview
Implement promiseAny(promises) that returns the first fulfilled promise. If all reject, throws an AggregateError.
Examples
await promiseAny([Promise.reject('a'), Promise.resolve('b')]); // 'b'Solution
Reveal solution
function promiseAny(promises) {
return new Promise((resolve, reject) => {
const errors = [];
let count = 0;
const arr = Array.from(promises);
if (arr.length === 0) reject(new AggregateError([], 'All promises were rejected'));
arr.forEach((p, i) => {
Promise.resolve(p).then(resolve, (err) => {
errors[i] = err;
count++;
if (count === arr.length) reject(new AggregateError(errors, 'All promises were rejected'));
});
});
});
}promise-any.js
Promise.any
mediumcodingJavaScriptPromises
Overview
Implement promiseAny(promises) that returns the first fulfilled promise. If all reject, throws an AggregateError.
Examples
await promiseAny([Promise.reject('a'), Promise.resolve('b')]); // 'b'Solution
Reveal solution
function promiseAny(promises) {
return new Promise((resolve, reject) => {
const errors = [];
let count = 0;
const arr = Array.from(promises);
if (arr.length === 0) reject(new AggregateError([], 'All promises were rejected'));
arr.forEach((p, i) => {
Promise.resolve(p).then(resolve, (err) => {
errors[i] = err;
count++;
if (count === arr.length) reject(new AggregateError(errors, 'All promises were rejected'));
});
});
});
}NameTopicDifficulty
103 of 103 problems