【问题标题】:Render page in express after for loop completes在 for 循环完成后以 express 呈现页面
【发布时间】:2016-02-06 19:49:26
【问题描述】:

我必须在 for 循环中重复运行 mongoose 查询,一旦完成,我想以 express 呈现页面。下面给出的示例代码。由于 mongoose 是异步运行的,我怎样才能让“commands/new”页面仅在 for 循环中填充“commands”数组后才呈现?

...
...
var commands = [];
for (var index=0; index<ids.length; index++) {
    mongoose.model('Command').find({_id : ids[index]}, function (err, command){
        // do some biz logic with the 'command' object
        // and add it to the 'commands' array
        commands[index] = command;
    });
}

res.render('commands/new', {
    commands : commands
});
...
...

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    您在此处的基本for 循环不尊重您在执行每次迭代之前调用的异步方法的回调完成。因此,只需使用可以代替的东西。节点async 库在这里符合要求,实际上是更好的数组迭代方法:

    var commands = [];
    
    async.each(ids,function(id,callback) {
        mongoose.model("Command").findById(id,function(err,command) {
            if (command) 
                commands.push(command);
            callback(err);
        });
    },function(err) {
       // code to run on completion or err
    })
    

    因此async.each 或可能像async.eachLimit 这样的变体将只运行有限数量的并行任务,这将是您更好的循环迭代控制方法。

    NB Mongoose 的.findById() 方法也有助于缩短此处的编码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2021-07-04
      • 2012-01-26
      • 1970-01-01
      • 2017-07-27
      相关资源
      最近更新 更多