Last active
November 27, 2016 13:05
-
-
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
This file contains hidden or 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
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