Skip to content

Instantly share code, notes, and snippets.

@jwulf
Last active March 5, 2020 03:16
Show Gist options
  • Save jwulf/919cb46fd4ca6a129356296d8141b22d to your computer and use it in GitHub Desktop.
Save jwulf/919cb46fd4ca6a129356296d8141b22d to your computer and use it in GitHub Desktop.
// 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