TIL AggregateError
POSTED ON:
TAGS: promises javascript mdn
I heard the term AggregateError in relations to Promise.Any
had to piece it all together.
Promise.any #
First, Promise.any is pretty straightforward.
The Promise.any() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an AggregateError containing an array of rejection reasons.
Promise.any + AggregateError 📖
Promise.any([
fetch('https://v8.dev/').then(() => 'home'),
fetch('https://v8.dev/blog').then(() => 'blog'),
fetch('https://v8.dev/docs').then(() => 'docs')
]).then((first) => {
// Any of the promises was fulfilled.
console.log(first);
// → 'home'
}).catch((error) => {
// All of the promises were rejected.
console.log(error);
});
So what is a AggregateError object?
via the MDN
The AggregateError object represents an error when several errors need to be wrapped in a single error. It is thrown when multiple errors need to be reported by an operation, for example by Promise.any(), when all promises passed to it reject.
So it's several errors being wrapped.
const promise1 = Promise.reject(new Error('Error 1'));
const promise2 = Promise.reject(new Error('Error 2'));
Promise.allSettled([promise1, promise2])
.then(results => {
const errors = results.filter(result => result.status === 'rejected')
.map(result => result.reason);
if (errors.length > 0) {
// new AggregateError(errors, message, options)
throw new AggregateError(errors, 'Multiple errors occurred');
}
})
.catch(error => {
console.log(error); // Multiple errors occured at line
console.log(error.message); // Multiple errors occured
console.log(error.name); // AggregateError
console.log(error.errors); // ['Error 1 at Line", 'Error 2 at line"]
});
via ES2021 Features!
Related TILs
Tagged: promises