Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 911
Jordan Scales Avatar asked Mar 30 '26 19:03

Jordan Scales


2 Answers

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'
});
like image 90
Michelle Tilley Avatar answered Apr 02 '26 20:04

Michelle Tilley


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.

like image 28
reagan Avatar answered Apr 02 '26 22:04

reagan