Last active
March 5, 2020 03:16
-
-
Save jwulf/919cb46fd4ca6a129356296d8141b22d to your computer and use it in GitHub Desktop.
A code example from the article https://www.joshwulf.com/blog/2020/03/array-async-failure
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
// Takes an array of async tasks that may throw of shape {run: () => Promise<result>} | |
// Returns Promise<{error: error[], success: result[]}> | |
async function executeAsyncTasks(arrayOfAsyncTasks) { | |
const success = async res => ({ success: await res }) // Promise<{success: res}> | |
const error = async err => ({ error: await err }) // Promise<{error: e}> | |
const runWithResult = task => task.run().then(success).catch(error) | |
const outcomes = await Promise.all(arrayOfAsyncTasks.map(runWithResult)) | |
const outcomesFlat = outcomes.reduce((acc, o) => o.error ? | |
{ error: [...acc.error, o.error], success: acc.success } : | |
{ error: acc.error, success: [...acc.success, o.success] }, | |
{ error: [], success: [] }) | |
return outcomesFlat | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment