FranzSilva87
FranzSilva87

Reputation: 91

Sending multiple emits inside a loop

We currently need to send data to multiple connected client, each of them have a unique channel name, for instance CHANNEL1, CHANNEL2, CHANNEL3 Etc. When trying to cycle through all the channels for example, 30.000 channels. It sends the first one, then it waits till the loop finishes before sending the rest.

io.on('connection', function (socket){
  socket.on('chat message', function (msg){      
      for (i = 0; i < 30000; i++) {
        io.emit('CHANNEL' + i, msg);
      }
  });
});

Is there a way it sends the emits asynchronously, while it loops 1 by 1?

Upvotes: 1

Views: 1321

Answers (1)

Jeff Sloyer
Jeff Sloyer

Reputation: 4964

The io.emit call is async. You should ideally call it and wait using a callback before calling it again.

The best approach would be to use the async library (https://github.com/caolan/async/, npm install asnyc, and using the each() method.

Upvotes: 1

Related Questions