javascript - node js :-null value error in for loop -
hi newbie on nodejs trying implement project in have event management site..where adding event page specific user.
now problem getting stuck @ point:-
exports.getdashboard=function(req,res){ var eventlist=[]; for(var i=0;i<req.user.invites.length;i++) { event.find({_id:req.user.invites[i]},function(err,events){ if(err) { console.log(err); } else { eventlist.push(events[0]); console.log(eventlist); // shows value inside array wanted } }); } console.log(eventlist); // shows null value why? variable in scope declaration res.render('dashboard'); };
explanation: created function in have variable eventlist declared , initialized every time function gets called. used variable eventlist inside inner function update value , concatenate previous values.. console.log shows eventlist getting updated wanted.but when try use variable outside the inner function doenst work , empty array initialized scope of variable local in main function , visible inside inner funciton when use after inner funciton ie outside loop array shows null value do?
the image below:- created function in have variable eventlist declared , initialized everytime function gets called. used variable eventlist inside inner function update value , concatenate previoys values.. console.log shows eventlist getting updated wanted.but when try use variable outside the inner function doenst work , empty array initialized scope of variable local in main function , visible inside inner funciton when use after inner function vanishes
what do?
you printing eventlist
before gets populated. appending items eventlist
inside event.find
callback might not have executed yet when outer console.log(eventlist);
.
edit:
print collection once callback called can check in callback if in last iteration, if so, print eventlist
.
if(i===(req.user.invites.length-1)){ console.log(eventlist); }
you could/should consider more elaborated async.js or promise library (as q). async.js code (not tested):
async.eachseries(req.user.invites, function (invite, callback) { event.find({_id:invite}, function(err,events){ if(err) { console.log(err); throw err; } else { eventlist.push(events[0]); console.log(eventlist); } } }, function (err) { // called once iteration callbacks have returned (or error thrown) if (err) { throw err; } console.log(eventlist); // final version of eventlist });
Comments
Post a Comment