socket.io - getting more than one field for a socket?

℡╲_俬逩灬. 提交于 2020-01-04 04:09:09

问题


I have the following code when a user disconnects. I want to emit a signal with the room name and user name.

client.get('nickname', function(err, name) {
  client.get('room', function(err2, room) {
    io.sockets.in(room).emit('disconnect', name);
  });
});

My question is, is there any way to avoid wrapping the .get calls like this? For my application, they are going to add up quickly. Can I get more than one value from one get() command? Or am I just handling this all wrong?


回答1:


If you need to get a lot of values, take a look at a flow control library like async. For example, here's how you might get several values from the client in parallel:

var async = require('async');

async.parallel([
  client.get.bind(this, 'nickname'),
  client.get.bind(this, 'room'),
  client.get.bind(this, 'anotherValue')
], function(err, results) {
  // here, `err` is any error returned from any of the three calls to `get`,
  // and results is an array:
  //    results[0] is the value of 'nickname',
  //    results[1] is the value of 'room',
  //    results[2] is the value of 'anotherValue'
});



回答2:


If you had all the attributes of a user in an object/array, and all the attributes of a room in an object/array, you'd still only need these 2 nested calls. You're doing it right.



来源:https://stackoverflow.com/questions/11405943/socket-io-getting-more-than-one-field-for-a-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!