Last active
August 29, 2015 14:24
-
-
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)
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 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