我试图询问房间中的任何客户是否有与他们相关的特定财产。socket.io get 方法的异步特性给我带来了问题。我已经看过异步库,它看起来可能是我需要的,但我很难想象如何将其应用于这种情况。
假设 get 不是异步的,这就是我希望函数的工作方式;
/**
*
**/
socket.on('disconnect', function(data) {
socket.get('room', function(err, room) {
if(!roomHasProperty(room)) {
io.sockets.in(room).emit('status', { message: 'property-disconnect' });
}
});
});
/**
*
**/
var roomClients = function(room) {
var _clients = io.sockets.clients(room);
return _clients;
}
/**
*
**/
var roomHasProperty = function(room) {
// get a list of clients in the room
var _clients = roomClients(room);
// build up an array of tasks to be completed
var tasks = [];
// loop through each socket in the room
for(key in _clients) {
var _socket = _clients[key];
// grab the type from the sockets data store and check for a control type
_socket.get('type', function (err, type) {
// ah crap, you already went ahead without me!?
if(type == 'property') {
// found a the property type we were looking for
return true;
}
});
}
// didn't find a control type
return false;
}
有没有更好的方法来做到这一点?