我只是做了我的第一个Node异步内容,我想对DB进行两次查询,然后依次打印结果,我的代码如下:
console.log(req.query);
function logAllThings(err,things){
if (err){
console.log(err);
} else {
console.log(things);
};
};
async.parallel([
function(callback) { //This is the first task, and callback is its callback task
Event.find({}, function(err, events) {
logAllThings(err,events);
});
},
function(callback) { //This is the second task, and callback is its callback task
Organisation.find({}, function(err,organisations) {
logAllThings(err,organisations);
}); //Since we don't do anything interesting in db.save()'s callback, we might as well just pass in the task callback
}
], function(err) { //This is the final callback
console.log('Both should now be printed out');
});
我遇到的问题是第二个函数(返回组织的函数)打印它们很好。然而,那个意味着返回事件的那个并不会返回{},尽管事实上我知道这个查询是有效的,因为我已经在别处测试了它。
任何帮助将不胜感激
由于
答案 0 :(得分:3)
你必须调用传递给每个瀑布函数的callback
函数,否则它不知道它何时完成。试试这个:
async.parallel([
function(callback) { //This is the first task, and callback is its callback task
Event.find({}, function(err, events) {
if (err) return callback(err);
logAllThings(err,events);
callback();
});
},
function(callback) { //This is the second task, and callback is its callback task
Organisation.find({}, function(err,organisations) {
if (err) return callback(err);
logAllThings(err,organisations);
callback();
}); //Since we don't do anything interesting in db.save()'s callback, we might as well just pass in the task callback
}
], function(err) { //This is the final callback
console.log('Both should now be printed out');
});