javascript - Change variable outside of function's scope -


so have current code:

exports.retrievemessages = function retrievemessages () {     var messages = [];     user_message.find({}, function(err, msgs) {         if (err) throw err;         // object of users         msgs.foreach(function(entry) {             messages.push({username: entry.username, message: entry.message});             //console.log(entry.message);             //console.log(entry.username);         });     });     console.log(messages);     return messages; } 

somehow messages still empty after user_messages.find(). there way push results onto messages variable? verified if move console.log(messages) foreach loop, print things, meaning messages see inside foreach loop different 1 outside.

also, because messages inside function local variable pushing onto different variable?

the problem appears user_message.find asynchronous. it's not until returns , calls inner callback messages have these new values pushed it, after outer function, retrievemessages returns.

any code depends on messages returned have invoked callback passed user_message.find.


Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -