Created
April 27, 2013 16:19
-
-
Save simov/5473645 to your computer and use it in GitHub Desktop.
Chaining asynchronous functions.
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
function chain () { | |
var funcs = arguments; | |
return function (args, cb) { | |
(function next (index) { | |
if (index == funcs.length) return cb(); | |
funcs[index](args, function (err) { | |
if (err) return cb(err); | |
next(++index); | |
}); | |
}(0)); | |
} | |
} | |
// async funcs | |
function func1 (args, next) { | |
console.log('func1 called'); | |
next(); | |
} | |
function func2 (args, next) { | |
console.log('func2 called'); | |
next(); | |
} | |
function func3 (args, next) { | |
console.log('func3 called'); | |
next(); | |
} | |
// init | |
var chain = chain(func1, func2, func3); | |
// some args | |
var args = {some: 'args'}; | |
// start | |
chain(args, function (err) { | |
if (err) throw err; | |
console.log('DONE!'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment