处理socket.io async get / set调用

时间:2013-05-09 10:59:42

标签: node.js socket.io node-async

我正在尝试询问房间中的任何客户是否有与之关联的特定属性。 socket.io get方法的异步性质给我带来了问题。我已经看到了async库,看起来它可能就是我需要的,但是我很难想象如何应用这种情况。

以下是我希望函数工作的方式,假设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;
}

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

你考虑过使用promises库吗?它使得处理异步函数变得更加容易。 如果你使用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');
  }
});