Getting more than one field for a socket?

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

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

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

+3
source share
2 answers

If you need to get a lot of values, take a look at a flow control library like async . For example, here, as you could 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' }); 
+4
source

If you had all the user attributes in the object / array and all the room attributes in the object / array, you still need only these two nested calls. You are doing it right.

+1
source

Source: https://habr.com/ru/post/1480879/


All Articles