我想使用Async.js瀑布同步运行一系列函数。一切都很好,除了我的MongoDB查询异步运行,尽管在同步瀑布函数内。给定一个包含5个对象的数组,在任务3开始之前,MongoDB步骤将针对所有5个对象运行!以下代码说明了我的流程:
// I want to send all 5 objects into the waterfall
var arrayOfObjects = [{name: 'Obj1'},{name: 'Obj2'},{name: 'Obj3'},{name: 'Obj4'},{name: 'Obj5'}]
// but for now just sending 1 object into waterfall
var myObject = {name: 'Obj1'};
async.waterfall([
async.apply(task1, myObject)
task2,
task3
], function(err, myObject){
console.log("Success!");
}
);
task1 = function(myObject, callback){
myObject.propA = "A";
callback(null, myObject);
}
// Check MongoDB with a query
task2 = function(myObject, callback){
Items.find({propB: "B"}, function(err, item){
if(item){
myObject.propB = item.propB;
callback(null, myObject);
}else{
return callback("Nothing with propB found!");
}
})
}
// call external API and wait on the response
task3 = function(myObject, callback){
FB.api('/563256426/feed', function(res, err){
myObject.propC = "C";
callback(null, myObject);
})
}
不幸的是,task2(涉及Mongo查询)立即运行。当给瀑布提供5个对象的数组时,task2将在所有5个对象上运行,然后其余代码(task3)可以完成运行。如何强制task3在下一个瀑布之前完成运行?