Skip to content

Commit 035c526

Browse files
committed
minor fixes
1 parent 5dea441 commit 035c526

File tree

1 file changed

+27
-2
lines changed
  • 1-js/11-async/08-async-await/04-promise-all-failure

1 file changed

+27
-2
lines changed

1-js/11-async/08-async-await/04-promise-all-failure/solution.md

+27-2
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,32 @@ function customPromiseAllWait(promises) {
8282

8383
Now `await customPromiseAllWait(...)` will stall the execution until all queries are processed.
8484

85-
This is a more reliable approach.
85+
This is a more reliable approach, as it guarantees a predictable execution flow.
8686

87-
Lastly, if we'd like to know about all the errors, e.g. for logging purposes, we can use `Promise.allSettled`.
87+
Lastly, if we'd like to process all errors, we can use either use `Promise.allSettled` or write a wrapper around it to gathers all errors in a single [AggregateError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError) object and rejects with it.
8888

89+
```js
90+
// wait for all promises to settle
91+
// return results if no errors
92+
// throw AggregateError with all errors if any
93+
function allOrAggregateError(promises) {
94+
return Promise.allSettled(promises).then(results => {
95+
const errors = [];
96+
const values = [];
97+
98+
results.forEach((res, i) => {
99+
if (res.status === 'fulfilled') {
100+
values[i] = res.value;
101+
} else {
102+
errors.push(res.reason);
103+
}
104+
});
105+
106+
if (errors.length > 0) {
107+
throw new AggregateError(errors, 'One or more promises failed');
108+
}
109+
110+
return values;
111+
});
112+
}
113+
```

0 commit comments

Comments
 (0)