javascript - Trying to pass a populated array to my res.render. Not sure how to make a proper async callback -


i trying write takes lists of ips database, , retrieves information servers, populates object, , passes object array. seem able make each object populate, , can tell, it's being passed array, when webpage loads (or console log of array), it's empty. have reason believe has being written synchronously. i'm still new async/sync differences , functionality. tried few different methods thought work, no matter what, seem getting empty array.

app.get('/', function (req,res) {   //1) read out entries database. db.all('select * servers', function (err,rows) {         var servers = rows;         var serverlist = [];       //2) parse each 1 each steamserverstatus         servers.foreach( function (server) {                  var ip = server.ip;                 var port = server.port;                 //3) populate array each object                 steamserverstatus.getserverstatus(ip, port, function (serverinfo) {                         var servertoken = {};                          servertoken.ip = ip;                         servertoken.servername = serverinfo.servername;                         servertoken.playercount = serverinfo.numberofplayers + "/" + serverinfo.maxnumberofplayers;                         serverlist.push(servertoken);                        }); // end serverstatus     }); // end foreach      //4) pass out our res.render         res.render('pages/index', { servers: serverlist }); }); //end db.all 

the array should getting populated, right? , if async issue, implementation make execution order work?

you can't use functions fetch results asynchronously in loop that. should instead using async.each:

var serverlist = []; async.each(servers, function eachserver(server, done) {   server.getitsthing(function onthing(err, thing) {     if (err) return done(err);     serverlist.push(thing);   }); }, function onallserversdone() {   res.render('pages/index', { servers: serverlist}); }); 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -