Nodejs async series - pass arguments to next callback
Another option is to use async.auto. With async auto you can specify the dependency data for a task and async will begin to run it when able to. There is a good example in the README.md, but here is roughly your series from above:
async.auto({
one: function(callback){
setTimeout(function(){
callback(null, 1);
}, 200);
},
// If two does not depend on one, then you can remove the 'one' string
// from the array and they will run asynchronously (good for "parallel" IO tasks)
two: ['one', function(callback, results){
setTimeout(function(){
callback(null, 2);
}, 100);
}],
// Final depends on both 'one' and 'two' being completed and their results
final: ['one', 'two',function(err, results) {
// results is now equal to: {one: 1, two: 2}
}];
});
You can chain together asynchronous functions with the async module's waterfall
function. This allows you to say, "first do x, then pass the results to function y, and pass the results of that to z." Copied from the [docs][1]:
async.waterfall([
function(callback){
callback(null, 'one', 'two');
},
function(arg1, arg2, callback){
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
},
function(arg1, callback){
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
You don't strictly need the async module to accomplish this; this function is designed to make the code easier to read. If you don't want to use the async module, you can always just use traditional callbacks.