Sending multiple emits inside a loop

2019-09-17 04:06发布

问题:

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?

回答1:

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.