【发布时间】:2015-06-05 15:05:03
【问题描述】:
我在 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。
我如何使用异步来实现这一点?
提前感谢并为这么长的问题道歉。
【问题讨论】:
标签: javascript node.js asynchronous express mongoose