在for循环完成后,快速渲染页面
我必须在for循环中反复运行mongoose查询,一旦完成,我想要显示一个页面。 示例代码如下。 由于mongooseasynchronous运行,我怎么才能使'命令/新'页面渲染只有'命令'数组已被填充在for循环?
... ... 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 }); ... ...
这里的基本for
循环不考虑执行每次迭代之前调用的asynchronous方法的callback完成。 所以简单地使用一些相反的东西。 节点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
这样只会运行有限数量的并行任务的变体将会是你更好的循环迭代控制方法。
注意Mongoose的.findById()
方法也有助于缩短编码时间。