Last active
February 18, 2022 15:20
-
-
Save Domiii/41c1dc504025e789fd8741f78d3ac528 to your computer and use it in GitHub Desktop.
A fix for Promise.all. Explanation here: https://dev.to/domiii/a-solution-to-the-deep-flaws-of-promiseall-4aon-temp-slug-8454028
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Fixes the "muted errors problem" of Promise.all. | |
* | |
* {@link betterPromiseAll} | |
* @see https://gist.github.com/Domiii/41c1dc504025e789fd8741f78d3ac528 | |
* @see https://dev.to/domiii/a-solution-to-the-deep-flaws-of-promiseall-1ldh | |
*/ | |
async function betterPromiseAll(promises) { | |
const results = await Promise.allSettled(promises); | |
const values = []; | |
const errors = []; | |
for (const result of results) { | |
if (result.status === 'rejected') { | |
errors.push(result.reason); | |
} | |
else { | |
values.push(result.value); | |
} | |
} | |
if (errors.length) { | |
// NOTE: `AggregateError` is also not mature YET. It's internal `errors` property is (currently, as of 2/2022) NOT rendered when reported, so we have to do it manually. | |
// throw new AggregateError(errors, 'Promise.allSettled rejections'); | |
throw new Error(`${errors.length} promise rejections: ${errors.map((err, i) => `\n [${i + 1}] ${err.stack || err}`).join('')}\n------`); | |
} | |
return values; | |
} | |
// /** ########################################################################### | |
// * some samples | |
// * ##########################################################################*/ | |
// async function runSample(cb) { | |
// try { | |
// const result = await cb(); | |
// console.log('########\nFULFILL:\n', result); | |
// } | |
// catch (err) { | |
// console.error('########\nREJECT:\n', err); | |
// } | |
// } | |
// // reject | |
// runSample(() => { | |
// return betterPromiseAll([ | |
// Promise.reject(1), | |
// Promise.reject(new Error(2)), | |
// Promise.resolve().then(() => { throw new Error(3); }) | |
// ]); | |
// }); | |
// // reject | |
// runSample(() => { | |
// return betterPromiseAll([ | |
// Promise.resolve(1), | |
// Promise.reject(new Error(2)), | |
// Promise.resolve().then(() => { throw new Error(3); }) | |
// ]); | |
// }); | |
// // fulfill | |
// runSample(() => { | |
// return betterPromiseAll([ | |
// Promise.resolve(1), | |
// Promise.resolve(2), | |
// Promise.resolve(3) | |
// ]); | |
// }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment