Skip to content

Instantly share code, notes, and snippets.

@Couto
Created April 17, 2012 19:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Couto/2408420 to your computer and use it in GitHub Desktop.
Save Couto/2408420 to your computer and use it in GitHub Desktop.
Walk along an array of asynchronous functions
/**
* walk
* small function to walk along an array of functions
* each function walked gets an extra argument
* that argument is a function that should be called
* to notify the walk function to step to the next function
* the arguments given at call time are passed to the next function
*
* @function
* @param {Array} fns Array of functions
* @returns undefined
*/
function walk(fns) {
(function next() {
var args = Array.prototype.slice.call(arguments);
fns.length && fns.shift().apply(this, args.concat(next));
}());
}
// Usage
function a(input, output, next) {
// do something asincronous
// call next when done, and pass values
// to the next function in line
next(value1, value2)
}
function b(value1, value2, next) {
// do something asincronous
// call next when done, and pass values
// to the next function in line
next(value1, value2)
}
walk([a,b]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment