Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active August 29, 2015 14:24
Show Gist options
  • Save mgtitimoli/a158ee257adf6753f652 to your computer and use it in GitHub Desktop.
Save mgtitimoli/a158ee257adf6753f652 to your computer and use it in GitHub Desktop.
Promise based serial task executor (version #1 - Only creates promises if any task returns one)
"use strict";
function isThenable(something) {
return (
typeof something === "object"
&& something.then instanceof Function
);
}
function serial(tasks, ...args) {
let results = [];
let error;
let prevPromise;
for (let curTask of tasks) {
if (prevPromise) {
prevPromise = prevPromise.then(function(prevResult) {
results.push(prevResult);
return curTask(...args);
});
}
else {
let curResult;
try {
curResult = curTask(...args);
}
catch(e) {
error = e;
break;
}
if (isThenable(curResult)) {
prevPromise = curResult;
}
else {
results.push(curResult);
}
}
}
if (error) {
return Promise.reject(error);
}
// none of the tasks returned a promise
if (!prevPromise) {
return Promise.resolve(results);
}
return prevPromise.then(function(prevResult) {
results.push(prevResult);
return results;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment