Skip to content

Instantly share code, notes, and snippets.

@akhawaja
Last active May 7, 2017 23:02
Show Gist options
  • Save akhawaja/9198db143b7914a7340e3b1c6ac0c997 to your computer and use it in GitHub Desktop.
Save akhawaja/9198db143b7914a7340e3b1c6ac0c997 to your computer and use it in GitHub Desktop.
Process a series of JavaScript functions in the order supplied.
/**
* Process a set of functions in order supplied.
*
* @author Amir Khawaja <[email protected]>
* @param {array} funcs - An array of functions
*/
function waterfall(funcs, done) {
if (funcs !== void 0 && funcs !== null) {
if (typeof funcs !== 'object' && funcs.shift !== void 0) {
throw new Error('Array of functions expected');
} else {
if (funcs.length === 0) {
throw new Error('Empty function array detected');
}
}
}
var lastReturnValue = null;
var runner = null;
var callback = function (err, results) {
if (err !== void 0 && err !== null) {
console.error(err);
}
lastReturnValue = results;
runner();
};
var dispatcher = function (fn, handler) {
try {
runner = handler;
window.setTimeout(fn.bind(null, lastReturnValue, callback), 0);
} catch (e) {
console.error(e);
}
};
(function run() {
if (funcs.length !== 0) {
dispatcher(funcs.shift(), run);
} else {
done && done(lastReturnValue);
}
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment