Write a function `promiseAny(promises)` that resolves with the first fulfilled promise. Rejects only if ALL reject.
Problem Statement
Write a function `promiseAny(promises)` that resolves with the first fulfilled promise. Rejects only if ALL reject.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Promise.any() resolves as soon as one promise fulfills.
š” Hint 2:
Track rejections; if all reject, reject with an AggregateError.
š” Hint 3:
Count rejections and reject when rejectCount === promises.length.
ā
Solution:
```javascript
function promiseAny(promises) {
return new Promise((resolve, reject) => {
let rejections = 0;
const errors = [];
promises.forEach((p, i) => {
Promise.resolve(p).then(resolve).catch(err => {
errors[i] = err;
rejections++;
if (rejections === promises.length) reject(errors);
});
});
});
}
```