Last active
August 29, 2015 14:24
-
-
Save mgtitimoli/2f0206d82ae85e85404f to your computer and use it in GitHub Desktop.
Promise based serial tasks executor (version #3: Create initial promise | Array.prototype.reduce)
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
"use strict"; | |
function serial(tasks, ...args) { | |
let results = []; | |
let lastPromise = tasks.reduce(function(prevPromise, curTask) { | |
return prevPromise.then(function(prevResult) { | |
results.push(prevResult); | |
return curTask(...args); | |
}); | |
}, Promise.resolve()); | |
return lastPromise.then(function(lastResult) { | |
results.push(lastResult); | |
// Remove first result since corresponds to the initial Promise | |
// created to be able to easily chain all the promises | |
results.shift(); | |
return results; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment