Skip to content

CodeNot attempted

Promise.any polyfill

Difficulty: medium

Implement Promise.any.

  • resolve with the first fulfilled value (failures before it don't matter)
  • if every input rejects, reject with an AggregateError whose errors are the reasons in input order
  • empty input rejects with AggregateError
Show reference solution
export function promiseAny<T>(values: Iterable<T | PromiseLike<T>>): Promise<T> {
const items = Array.from(values);
const errors: unknown[] = [];
let count = 0;
return new Promise((resolve, reject) => {
if (items.length === 0) {
reject(new AggregateError([], 'All promises were rejected'));
return;
}
for (let i = 0; i < items.length; i++) {
Promise.resolve(items[i])
.then((value) => resolve(value)) // the first success wins
.catch((error) => {
errors[i] = error;
count++;
if (count === items.length) {
reject(new AggregateError(errors, 'All promises were rejected'));
}
});
}
});
}
Loading editor…