This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
34. implement `Promise.any()`
Here's one possible implementation of Promise.any()
:
class AggregateError extends Error {
constructor(message, errors) {
super(message);
this.name = 'AggregateError';
this.errors = errors;
}
}
Promise.any = function(promises) {
return new Promise((resolve, reject) => {
const errors = [];
let resolved = false;
for (const promise of promises) {
promise.then(
value => {
if (!resolved) {
resolved = true;
resolve(value);
}
},
error => {
errors.push(error);
if (errors.length === promises.length) {
reject(new AggregateError('No Promise in Promise.any was resolved', errors));
}
}
);
}
});
};
// Example usage:
const promise1 = new Promise(resolve => setTimeout(() => resolve('hello'), 100));
const promise2 = new Promise((_, reject) => setTimeout(() => reject(new Error('error')), 200));
const promise3 = new Promise(resolve => setTimeout(() => resolve('world'), 300));
Promise.any([promise1, promise2, promise3])
.then(console.log) // outputs "hello"
.catch(console.error); // will not be called
The implementation creates a new Promise
and loops through the input promises, adding then
and catch
handlers to each one. When a promise fulfills, the then
handler checks if a promise has already been resolved; if not, it resolves the new promise with the value from that promise. When a promise is rejected, the catch
handler adds the error to an array of errors, and checks if all promises have been rejected; if so, it rejects the new promise with an AggregateError
.