我有一个简单的函数,它返回通道中已连接用户的列表,我在初始阶段使用一个简单的数组,但是知道,我想从 mongodb 数据库中检索一些用户详细信息并将其添加到该数组中。
我遇到的问题是返回结果为空,稍后我可以在控制台日志中清楚地看到,这是因为查询运行较晚并且返回在返回结果之前运行。
我知道这是因为异步函数,我已经尝试过 Q 和其他函数,但我只是无法让它工作。:(
//GET USERS FOR SPECIFIED ROOM
function get_room_users( room ){
// create an array to hold all the usernames of the poeple in a specific room
var roomusers = new Array();
// get all the clients in ‘room1′
var clients = io.sockets.clients( room );
var i = 0;
for(var i = 0; i < 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 THE CONSOLE SHOWS ROOMUSERS FILLED IN");
console.log(roomusers);
i++;
}
});
}
console.log("HERE THE ARRAY LOOKS EMPTY BEFORE SENDING BACK");
console.log(roomusers);
return roomusers;
}
var users = get_room_users(room1);
console.log("HERE THE ARRAY LOOKS EMPTY!")
console.log(users);
控制台日志结果
HERE THE ARRAY LOOKS EMPTY BEFORE SENDING BACK
[]
HERE THE ARRAY LOOKS EMPTY!
[]
HERE THE CONSOLE SHOWS ROOMUSERS FILLED IN
['user@user.com']
最终解决: 好的,正如其中一位用户评论的那样,我在考虑同步模式,我在解决 bucle 后更改了 emit 方法,以便在所有操作完成后发出。请记住,我使用 Q 来创建承诺 :)
//获取指定房间的用户 function get_room_users( room ){
var the_promises = [];
// create an array to hold all the usernames of the poeple in a specific room
var roomusers = new Array();
// get all the 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 to everyone in room 1 the usernames of the clients connected.
io.sockets.to( room ).emit('updateroomusers', roomusers);
} );
}