[英]How to call async.each in an external function having async.waterfall inside async.each
我在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
};
现在,我的firstOrderfunction
再次具有async.each
嵌入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;
innternalCallBack(null,a);
},
function(a,internalCallBack){
console.log("Computing Inner Second Waterfall");
b =14;
c = a*b;
innternalBack(null,c)
}
],function(err,c){
if(err){
console.log("Error is == " +err);
}else{
d = c;
console.log("The Returned Value is == "+c);
innerCallBack(null,d);
}
});//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
}
我得到的输出是
在第一个回电
称为外部功能
计算位置
计算位置
计算内部第一个瀑布
计算内部第一个瀑布
返回值已处理
在第二次回电中
返回值为== NaN
我希望所有内容按以下顺序同步运行。
在demo.findone的exec回调中调用async.waterfall
调用firstOrderFunction
在firstOrderFunction内部调用async.each
在async.each中调用async.waterfall
调用第一个回调函数,返回a = 14。
调用第二个回调函数,返回c = 14 * 14 = 196。
如何使用异步实现此目的?
预先感谢您道歉这么长时间的问题。
在async.waterfall()的末尾调用async.each()的回调,并在async.each()的末尾调用firstOrderFunction的回调。 这是修改后的代码:
function fistOrderFunction(demosReturned, callback){
var ret = [];
console.log("Called the External Function");
async.each(demosReturned.locations, function(location, eachCb) {
console.log('Computing Location #');
async.waterfall([
function(waterfallCb){
console.log("Computing Inner First Waterfall");
a = 14;
waterfallCb(null,a);
},
function(a,waterfallCb){
console.log("Computing Inner Second Waterfall");
b =14;
c = a*b;
waterfallCb(null,c)
}
],function(err,c){
if(err){
console.log("Error is == " +err);
eachCb(err);
}else{
ret.push(c);
console.log("The Returned Value is == "+c);
eachCb(null);
}
});//End Async.Waterfall
},function(err){
if(err){
console.log("The Error in Async.Each === " + err);
callback(err, null);
}else{
console.log("The Returned Value is Processed ");
callback(null, ret);
}
}); //End Async.Each
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.