我有一个简单的函数,它返回一个通道中已连接用户的列表,我在初始阶段使用它有一个简单的数组,但是知道,我想从mongodb数据库中检索一些用户详细信息并将其添加到那个阵列。
我遇到的问题是返回结果是空的,我可以在控制台日志中清楚地看到,这是因为查询运行较晚并且返回正在运行,然后才返回结果。 / p>
我知道这是因为异步功能,我尝试过使用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创建promisses:)
//获取指定房间的用户 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);
} );
}
答案 0 :(得分:1)
我建议您使用Q Promises(https://npmjs.org/package/q)。 Promises是一个非常强大的工具,用于调度异步操作。
答案 1 :(得分:0)
是的,这是在异步环境中使用同步样式的问题。在回复之前,执行在io.sockets.clients( room )
之前运行。
以下内容应该有效:
io.sockets.clients(room).forEach(function (socket) {
// Your for-loop code
db.users.findOne( ... );
});