Skip to content

Instantly share code, notes, and snippets.

@qubyte
Created September 24, 2012 16:39
Show Gist options
  • Save qubyte/3776903 to your computer and use it in GitHub Desktop.
Save qubyte/3776903 to your computer and use it in GitHub Desktop.
Simple series execution for asynchronous functions.
/*
* Inspired by the async module, but only needing async.series, I decided to code something minimal.
*
* funcs is an array of functions taking a single argument (a callback). It is assumed that these functions
* operate with/on data outside of the local scope. The functions thus form a series of steps. cb is a
* a final callback, which is called if a function in the series is handed an error (zeroth argument of any
* function in the series as per convention) or otherwise when all functions in the array have been called.
* Functions are called in order, from zeroth element up.
*
* The original async.forEachSeries assembles other callback arguments into an array. This can be easily
* engineered in, but I find that I almost never use that feature, so this function leaves it out. Finally,
* the array passed into the function is emptied by the function. Again, this can be avoided easily, but
* has never been necessary for me.
*/
function asyncSeries(funcs, cb) {
function worker(err, funcs) {
if (err || !funcs.length) {
return cb(err);
}
return funcs.shift()(callNext);
}
function callNext(err) {
return worker(err, funcs);
}
return worker(null, funcs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment