for循环完成后,在express中渲染页面

时间:2016-02-06 10:57:51

标签: node.js mongodb mongoose mongodb-query

我必须在for循环中重复运行mongoose查询,一旦完成,我想在express中呈现一个页面。示例代码如下。由于mongoose是异步运行的,所以只有在for循环中填充'commands'数组后,如何才能使'commands / new'页面呈现?

...
...
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
});
...
...

1 个答案:

答案 0 :(得分:2)

此处的基本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或可能像[{1}}这样只会运行有限数量的并行任务的变体将是你在这里更好的循环迭代控制方法。

注意:Mongoose的async.eachLimit方法也有助于缩短编码。