Skip to content

Instantly share code, notes, and snippets.

@sktt
Last active November 27, 2016 13:05
Show Gist options
  • Save sktt/22e9a6e982469ae0dacc to your computer and use it in GitHub Desktop.
Save sktt/22e9a6e982469ae0dacc to your computer and use it in GitHub Desktop.
This is a pretty clean way to run sync and async tasks using Promise and a reducer func
module.exports = run
// Run tasks in sequence or async can be done in a very expressive way using
// Promise and a reducer
function run(tasks) {
return tasks.reduce(
(acc, task) => acc.then(lastResult => {
if (typeof task === 'function') {
// A task is a function that takes a result from a previous task and returns
// a promise executor function
return new Promise(task(lastResult))
} else {
// If it's an array of tasks, each task is run asyncronously
// and continues after all async task if finished
return Promise.all(task.map(t => new Promise(t(lastResult))))
}
}), Promise.resolve()
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment