node.js - Render page in express after for loop completes -


i have run mongoose query repeatedly within loop , once completes, want render page in express. sample code given below. since mongoose runs asynchronously, how can make 'commands/new' page render once 'commands' array has been populated within loop?

... ... var commands = []; (var index=0; index<ids.length; index++) {     mongoose.model('command').find({_id : ids[index]}, function (err, command){         // biz logic 'command' object         // , add 'commands' array         commands[index] = command;     }); }  res.render('commands/new', {     commands : commands }); ... ... 

your basic for loop here not respect callback completion of asynchronous methods calling before executing each iteration. use instead. node async library fits bill here, , in fact better methods of array iteration:

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 run on completion or err }) 

and therefore async.each or possibly variant async.eachlimit run limited number of parallel tasks set better loop iteration control methods here.

nb .findbyid() method of mongoose helps shorten coding here.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -