我正在构建一组对象,以便从csv流中保存在mongoDB中。对于每个csv行,在保存MongoDB中不存在一个或多个对象之前,我需要进行验证。下面的代码运行在GET路由中。
我一直在尝试使用异步瀑布,但它的行为并不像我所期望的那样。
这是代码
async.waterfall([
function (callback) {
console.log('in function 1');
--> Diagnosis.findOne({name: diagnosisName}, function (doc){
console.log(JSON.stringify(doc))
})
callback(null);
},
function (callback) {
console.log('in function2')
callback(null)
}],
function(err, results) {
console.log('finished!')
res.send("complete");
})--我希望这会返回以下
在function1中
JSON中的doc对象
在function2中
完成了!
,我得到了
在职能1中
在function2中
完成了!
空
只要没有findOne()调用,它就会按预期运行。我遗漏了什么??
非常感谢
发布于 2015-06-17 21:15:43
findOne是一个异步函数。您需要将回调移到此函数内,以遵循您所期望的顺序。
async.waterfall([
function(callback) {
console.log('in function 1');
Diagnosis.findOne({name: diagnosisName}, function(doc) {
console.log(JSON.stringify(doc));
callback(null);
});
},
function(callback) {
console.log('in function2');
callback(null);
}
],
function(err, results) {
console.log('finished!');
res.send("complete");
}
);但是为什么不使用内部承诺(或者另一个承诺库)呢?
console.log('in function 1');
// exec creates a new promise
Diagnosis.findOne({name: diagnosisName}).exec(function(doc) {
console.log(JSON.stringify(doc));
// resolve this with doc
return doc;
}).then(function(doc) {
console.log('in function2');
// resolve this with doc
return doc;
}).then(results) {
// results here is just doc from the previous resolution
console.log('finished!');
res.send("complete");
});发布于 2015-06-17 21:19:02
在你的第一个职能中:
function (callback) {
console.log('in function 1');
--> Diagnosis.findOne({name: diagnosisName}, function (doc){
console.log(JSON.stringify(doc))
})
callback(null);
},您的回调是在调用findOne之后调用的,这是异步的。无论何时完成findOne,您都应该使用回调。这意味着:
function (callback) {
console.log('in function 1');
--> Diagnosis.findOne({name: diagnosisName}, function (doc){
console.log(JSON.stringify(doc))
callback(null);
})
},甚至更好
function (callback) {
console.log('in function 1');
--> Diagnosis.findOne({name: diagnosisName}, callback);
},
function (callback, doc) {
console.log(JSON.stringify(doc))
callback(null);
},https://stackoverflow.com/questions/30902375
复制相似问题