Coding Challenge Practice - Question 94
Source: Dev.to
Problem Description
Implement Promise.any(). The function receives an array of promises and returns a single promise that resolves with the value of the first fulfilled promise, or rejects with an AggregateError containing all rejection reasons if every promise rejects.
Boilerplate
function any(promises) {
// your code here
}
Implementation Details
- Store each rejection reason, track how many promises have fulfilled, and keep the total number of promises.
- If the input array is empty, reject immediately with an
AggregateError.
const errors = [];
let rejectedCount = 0;
const total = promises.length;
if (total === 0) {
reject(new AggregateError([], 'All promises were rejected'));
return;
}
- Iterate over the promises, normalising each with
Promise.resolve.
promises.forEach((promise, index) => {
Promise.resolve(promise).then(
// As soon as one promise fulfills, resolve
value => {
resolve(value); // first fulfilled value wins
},
// If a promise rejects, store the error
error => {
errors[index] = error;
rejectedCount++;
// If all promises have rejected, reject with AggregateError
if (rejectedCount === total) {
reject(new AggregateError(errors, 'All promises were rejected'));
}
}
);
});
Final Code
function any(promises) {
return new Promise((resolve, reject) => {
const errors = [];
let rejectedCount = 0;
const total = promises.length;
if (total === 0) {
reject(new AggregateError([], "All promises were rejected"));
return;
}
promises.forEach((promise, index) => {
Promise.resolve(promise).then(
value => {
resolve(value);
},
error => {
errors[index] = error;
rejectedCount++;
if (rejectedCount === total) {
reject(new AggregateError("All promises were rejected", errors));
}
}
);
});
});
}