javascript - NodeJS + MongoDB ASYNC results appearing late -
i have simple function returns list of connected users in channel, using in initial stage simple array, know, want retrieve user details mongodb database , add array.
the problem i'm having return giving empty result, can see later on in console log because queries running late , return running before having results back.
i know because asynchronous functions, i've tried q , others cant working. :(
//get users specified room function get_room_users( room ){ // create array hold usernames of poeple in specific room var roomusers = new array(); // clients in ‘room1′ var clients = io.sockets.clients( room ); var = 0; for(var = 0; < clients.length; i++) { db.users.findone( { email: clients[i].username }, function(err, userdata) { if( err || ! userdata ){ console.log('no user found'); } else { console.log("displaying user data: " + userdata.nickname); roomusers[roomusers.length] = userdata.nickname; console.log("here console shows roomusers filled in"); console.log(roomusers); i++; } }); } console.log("here array looks empty before sending back"); console.log(roomusers); return roomusers; } var users = get_room_users(room1); console.log("here array looks empty!") console.log(users);
console log result
here array looks empty before sending [] here array looks empty! [] here console shows roomusers filled in ['user@user.com']
finally resolved: ok, 1 of users commented thinking in synchronous mode, changed emit method after bucle got resolved in order emit when has been done. keep in mind i'm using q create promisses :)
//get users specified room function get_room_users( room ){
var the_promises = []; // create array hold usernames of poeple in specific room var roomusers = new array(); // clients in ‘room1′ var clients = io.sockets.clients( room ); clients.foreach(function (socket) { var deferred = q.defer(); db.usuarios.findone( { email: socket.username }, function(err, userdata) { if( err || ! userdata ){ console.log('no user found'); deferred.reject(); } else { console.log("displaying user data: " + socket.username); roomusers[roomusers.length] = socket.username; console.log("dentro del bucle"); console.log(roomusers); deferred.resolve(); } }); the_promises.push(deferred.promise); }); q.all(the_promises).done( function(){ console.log("all things done!"); // broadcast in room 1 usernames of clients connected. io.sockets.to( room ).emit('updateroomusers', roomusers); } );
}
i suggest use q promises (https://npmjs.org/package/q). promises powerfull tool scheduling asynchronous operations.
Comments
Post a Comment