I spent quite a bit of time solving this issue because I encountered similar situation. I tried both async.series
and async.waterfall
.
async.series
:
Used a variable to share across the callback functions. I am not sure whether this is the best way to do it. I must give credit to Sebastian for his wonderful article about async
.
var async1 = require('async');
exports.asyncSeries1 = function (req, res, callback) {
var sharedData = "Data from : ";
async1.series([
// First function
function(callback) {
sharedData = "First Callback";
callback();
},
// Second function
function(callback){
console.log(sharedData);
sharedData = "Second Callback";
callback();
}
],
// Final callback
function(err) {
console.log(sharedData);
if (err) {
callback();
}
callback();
}
);
};
async.waterfall
: I tried using another callback function using async.apply
. Here is the piece of code that helped me solve the problem.
`
var async2 = require('async')
exports.asyncWaterfall1 = function (arg1, arg2, cb) {
async2.waterfall([
// async.apply
async2.apply(assignVariables, arg1, arg2),
// First callback
function(arg1, arg2, callback){
console.log(arg1);
console.log(arg2);
arg1 = 5;
arg2 = 6;
callback(null, arg1, arg2);
},
// Second callback
function(arg1, arg2, callback){
// arg1 now equals 'one' and arg2 now equals 'two'
console.log(arg1);
console.log(arg2);
arg1 = 7;
arg2 = 8;
callback(null, arg1, arg2);
}
],
function (err, arg1, arg2) {
console.log(arg1);
console.log(arg2);
});
};
// Method to assign variables
function assignVariables(arg1, arg2, callback) {
console.log(arg1);
console.log(arg2);
arg1 = 3;
arg2 = 4;
callback(null, arg1, arg2);
};
PS: Credit.