3

我试图询问房间中的任何客户是否有与他们相关的特定财产。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;
}

有没有更好的方法来做到这一点?

4

1 回答 1

0

您是否考虑过使用 Promise 库?它使处理异步函数变得更加容易。如果您要使用Q,您可以这样做:(对不起,我现在无法检查代码,但我很确定它应该几乎无需更改即可工作)

var roomHasProperty = function(room) {
  // Create the deferred object
  var deferred = Q.defer(); 
  // get a list of clients in the room
  var _clients = roomClients(room);
  // array of promises to check
  var promises = [];

  // This function will be used to ask each client for the property
  var checkClientProperty = function (client) {
    var deferred = Q.defer();
    // grab the type from the sockets data store and check for a control type
    client.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
        deferred.resolve(true);
      } else {
        // property wasn't found
        deferred.resolve(false);
      }
    });
    return deferred.promise;
  }
  // loop through each socket in the room
  for(key in _clients) {
    promises.push(checkClientProperty(_clients[key]));
  }
  Q.all(promises).then(function (results) {
    deferred.resolve(results.indexOf(true) > -1);
  })
  // didn't find a control type
  return deferred.promise;
}

您可以像这样使用它:

checkClientProperty(client).then(function (result) {
  if (result) {
    console.dir('the property was found');
  } else {
    console.dir('the property was not found');
  }
});
于 2014-01-28T20:03:49.423 回答