mardi 31 mars 2015

How to call async.each in an external function having async.waterfall inside async.each

I have a exports module in Node.JS



exports.doSomethingImportant= function(req, res) {
var id = req.params.id;
Demo.findOne({'_id': id})
.exec(function(err, demosReturned) {
async.waterfall([
function(outerCallBack){
console.log("In the First Call Back");
firstOrderFunction(demosReturned,outerCallBack);
},
function(x,outerCallBack){
var y =3
var z = x*y;
console.log("In the Second Call Back");
outerCallBack(null,z);
}
],function(err,z){
if(err){
console.log("Error is == " +err);
}else{
console.log("The Returned Value is == "+z);
}
});
});//End Demo.findOne
};


Now, my firstOrderfunction again has a async.each embedding async.waterfall



function fistOrderFunction(demosReturned,outerCallBack){
console.log("Called the External Function");


async.each(demosReturned.locations, function(location, innerCallBack) {
console.log('Computing Location #');

async.waterfall([
function(internalCallBack){
console.log("Computing Inner First Waterfall");
a = 14;
innerCallBack(null,a);
},
function(a,internalCallBack){
console.log("Computing Inner Second Waterfall");
b =14;
c = a*b;
innerCallBack(null,c)
}
],function(err,c){
if(err){
console.log("Error is == " +err);
}else{
d = c;
console.log("The Returned Value is == "+c);
}
});//End Async.Waterfall
},function(err,d){
if(err){enter code here
console.log("The Error in Async.Each === " + err);
}else{
console.log("The Returned Value is Processed ");
outerCallBack(null, d);
}
}); //End Async.Each
}


The Output I get is





In the First Call Back


Calculating Payments Called in First CallBack


Computing Location #


Computing Location #


Computing Inner First Waterfall


Computing Inner First Waterfall


The Returned Value is Processed


In the Second Call Back


The Returned Value is == NaN



I want everything to be run synchronously in the following order.





  1. Call async.waterfall in exec call back of Demo.findone




  2. Call the firstOrderFunction




  3. Call async.each inside firstOrderFunction




  4. Call async.waterfall inside async.each




  5. Call the first callback function returning a=14.




  6. Call the second callback function returning c =14*14 =196.





How do I achieve this using async?


Thanks in advance and apology for such a long question.


Aucun commentaire:

Enregistrer un commentaire