【发布时间】:2015-11-03 20:13:48
【问题描述】:
一直在努力解决这个问题,所以我想看看是否有人能快速回答。一直在尝试让异步工作进行并行调用,并设法做到了(感谢其他人:))。
但是,我现在遇到了需要将变量发送到回调函数的问题。基本上,我正在尝试使用 mongoose 向数据库发出五个请求以在表中查找级别 0-5。
设置一个从0迭代到4的for循环,每个循环进行一次query.push。一旦该循环完成,它就会调用 async.parallel 来等待回复。所有这些都有效,除了读取 i,它包含 0-4 之间的数字。起初我以为我可以通过在闭包中添加 (i) 来发送它。但这会阻止对 async.parallel 的调用(认为它找到它并将其识别为不是函数)。 认为绑定是答案,但不确定我应该绑定什么。
console.log("Lets see if we can't figure out this one once and for all");
var queries= [];
var maxLevels = 1;
for ( var i = 0; i < maxLevels; i++ ){
console.log("Looking for "+ i)
queries.push(function (cb) {
console.log("Seaching for "+ i)
Skill.find({level: i}).exec(function (err, docs) {
if (err) {
throw cb(err);
}
// do some stuff with docs & pass or directly pass it
cb(null, docs);
});
});
}
console.log("In theory we now have 5 requests");
async.parallel(queries, function(err, docs) {
// if any query fails
if (err) {
throw err;
}
console.log("This is what we got back")
for (var doc in docs){
console.log("Lets find 0")
cuDoc = docs
if (cuDoc === undefined ){
console.log("Got nothing on "+ cuDoc);
} else {
console.log("Looking at " + cuDoc);
}
}
})
【问题讨论】:
-
将
var i替换为let i并将 --harmony 标志添加到您的应用启动命令中。node --harmony app
标签: node.js asynchronous mongoose