【问题标题】:async parallel and using bind for iteration异步并行并使用绑定进行迭代
【发布时间】: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);
        }

    }

})

【问题讨论】:

标签: node.js asynchronous mongoose


【解决方案1】:

为什么不使用 find({level: { $gte: 0, $lte: 5 }}) 之类的东西?如果您希望查询只匹配整数,可以使用{$in: [0,1,2,3,4,5]}

无论如何,我会使用async.each,它似乎更适合使用索引,如下所示:

var array = ['level 0', 'level 1', 'level 2', 'level 3', 'level 4'];
async.each(array, function(element, callback){
    console.log("element : "+ element);
    console.log("array.indexOf(element) : "+array.indexOf(element));
    /* query here */
    callback();
},function(){
    /* stuff there */
    console.log("done");
})

这是控制台:

debugger listening on port 47025
element : level 0
array.indexOf(element) : 0
element : level 1
array.indexOf(element) : 1
element : level 2
array.indexOf(element) : 2
element : level 3
array.indexOf(element) : 3
element : level 4
array.indexOf(element) : 4
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    相关资源
    最近更新 更多