我最近开始使用async api。现在我的要求是在3个集合上执行连接 即字段,脚本和语句。字段可以有多个脚本,脚本可以有多个语句。
这是我到目前为止所尝试的内容:(使用脚本加入Fields集合)
// 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
即使数据库中有2个脚本,上述输出也不会打印任何脚本。我的数据库是在MongoDB中,我使用的是NodeJs,MongoJS api。为什么db.scripts.find()返回空数组? 任何帮助表示赞赏
我测试了这段代码,看看脚本是否返回o / p。请在下面找到我的代码
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"
}
]
答案 0 :(得分:1)
我能够解决问题。有2个问题(1)我的回调函数名称相同,即内部和外部回调嵌套在彼此之内。 (2)我不得不使用toString()而不是valueOf()