Implement Promise.any
The mirror image of Promise.all: resolve the instant any one input succeeds, and only reject — with an AggregateError — once every input has failed.
The problem
Reimplement `Promise.any()`. It takes an iterable of values — promises or plain values — and returns a promise that resolves with the value of the first input to fulfill.
It rejects only when every input rejects, and the rejection is an `AggregateError` whose `errors` array holds each input's reason in order. So where Promise.all is 'all must succeed,' Promise.any is 'one is enough.'
The approach
It's Promise.all turned inside out, so the structure mirrors it: the first `.then` to fire calls `resolve(val)` and wins — the once-only settle rule discards every later input, exactly like race but only for successes.
The bookkeeping lives on the failure side instead. I keep an `errors` array written by index and a `rejectCount`; each `.catch` records its reason and bumps the count, and `.finally()` checks whether everything has now rejected. Only when `rejectCount` equals the length do I `reject` with an `AggregateError` carrying all the collected reasons.
The solution
/**
* @param {Array<Promise>} promises
* @return {Promise}
*/
function any(promises) {
// your code here
return new Promise((resolve, reject) => {
if(!promises.length) resolve([])
let errors = Array(promises.length).fill(null)
let rejectCount = 0
for(let i=0;i<promises.length;i++) {
Promise.resolve(promises[i]).then((val) => {
resolve(val)
}).catch((e) => {
rejectCount++
errors[i] = e
}).finally(() => {
if(rejectCount == promises.length) {
reject(new AggregateError('No Promise in Promise.any was resolved', errors))
}
})
}
})
}Time O(n)Space O(n)