Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active August 29, 2015 14:24
Show Gist options
  • Save mgtitimoli/2f0206d82ae85e85404f to your computer and use it in GitHub Desktop.
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)
"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