Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active August 29, 2015 14:24
Show Gist options
  • Save mgtitimoli/819dd223a7075a6201dd to your computer and use it in GitHub Desktop.
Save mgtitimoli/819dd223a7075a6201dd to your computer and use it in GitHub Desktop.
Promise based serial tasks executor (version #2: Create initial promise | for of)
"use strict";
function serial(tasks, ...args) {
let results = [];
let prevPromise = Promise.resolve();
for (let curTask of tasks) {
prevPromise = prevPromise.then(function(prevResult) {
results.push(prevResult);
return curTask(...args);
});
}
return prevPromise.then(function(prevResult) {
results.push(prevResult);
// 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