async.each嵌套在async.waterfall中

我最近开始使用asynchronousAPI。 现在我的要求是在3个集合即字段,脚本和语句上执行连接。 字段可以有多个脚本,脚本可以有多个语句。

这是我迄今为止所尝试的:(用脚本joinFields集合)

// Array to hold async tasks var asyncTasks = []; async.waterfall([ function(callback){ // fetches fields based on some Id and it returns 2 fields db.fields.find({entity_id: mongojs.ObjectId("54440a448bbbcbb4070131ab")}, function (err, fields) { console.log(JSON.stringify(fields, null, 2)); callback(null, fields); }) }, function(arg1, callback){ // arg1 now equals fields arg1.forEach(function(eachField){ asyncTasks.push(function(callback){ db.scripts.find({fieldId: eachField._id.valueOf()}, function(err, scripts) { // Async call is done then alert via callback console.log(JSON.stringify(scripts, null, 2)); callback(null, scripts); }); }); }); // Now we have an array of functions doing async tasks // Execute all async tasks in the asyncTasks array async.parallel(asyncTasks, function(err, results) { // All tasks are done now console.log("Scripts" + JSON.stringify(results, null, 2)); callback(null, "done"); }); } ], function (err, result) { console.log(result); }); 

 // for the above code here is what i get the output [ { "_id": "54440a548bbbcbb4070131ac", "name": "t1", "type": "String", "entity_id": "54440a448bbbcbb4070131ab" }, { "_id": "54447f1d20c103981fa1a27c", "name": "t2", "type": "String", "entity_id": "54440a448bbbcbb4070131ab" } ] size of array 2 [] [] Scripts[ [], [] ] done 

上面的输出不会打印任何脚本,即使数据库中有两个脚本。 我的数据库是在MongoDB中,我正在使用NodeJs,MongoJS api。 为什么db.scripts.find()返回空数组? 任何帮助表示赞赏

我testing了这段代码,看看脚本是否返回o / p。 请在下面find我的代码

  test2(); function test2(){ var getScriptFunction = function(eachField, doneCallback){ if(eachField !== undefined) { var fieldId = eachField; console.log(fieldId); db.scripts.find({fieldId: fieldId}, function (err, result) { // Async call is done, alert via callback doneCallback(null, result); }); } } // The array is the id of fields async.map(["54440a548bbbcbb4070131ac", "54447f1d20c103981fa1a27c"], getScriptFunction, function (err, results) { // Square has been called on each of the numbers // so we're now done! if (err){ console.log("error!" + err); } else { console.log("printed from helper function \n" + JSON.stringify(results, null, 2)); } }); } 

这是上面代码的o / p来获取脚本单独运行

 printed from helper function [ [ { "_id": "54440a678bbbcbb4070131ad", "name": "s1", "fieldId": "54440a548bbbcbb4070131ac" }, { "_id": "544af260eb7a486824a5c306", "name": "s2", "fieldId": "54440a548bbbcbb4070131ac" } ], [] ] 

这是字段的样子(db.fields.find()。pretty())

 [ { "_id": "54440a548bbbcbb4070131ac", "name": "t1", "type": "String", "entity_id": "54440a448bbbcbb4070131ab" }, { "_id": "54447f1d20c103981fa1a27c", "name": "t2", "type": "String", "entity_id": "54440a448bbbcbb4070131ab" } ] 

我能解决这个问题。 有两个问题(1)我有相同的名称为callback函数,即内部和外部callback嵌套在对方。 (2)我不得不使用toString()而不是valueOf()