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?
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'
});
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.