The task is to implement promise.any().
The boilerplate code
function any(promises) {
// your code here
}
Promise.any receives an array of promises and returns a single promise that resolves from the value of that promise.
return new Promise((resolve, reject) => {
})
Store each rejection reason, track how many promises fulfilled and total number of promises.
const errors = [];
let rejectedCount = 0;
const total = promises.length;
If there are no promises, reject
if (total === 0) {
reject(new AggregateError([], 'All promises were rejected'));
return;
}
Ensure promises work correctly
promises.forEach((promise, index) => {
Promise.resolve(promise).then(
As soon as one promise fulfills, resolve
value => {
resolve(value); // first fulfilled value wins
},
If all promises fail
error => {
errors[index] = error;
rejectedCount++;
if (rejectedCount === total) {
reject(new AggregateError(errors, 'All promises were rejected'));
}
}
The final code
function any(promises) {
// your code here
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))
}
}
)
})
})
}
That's all folks!
Top comments (0)