Sending multiple emits inside a loop

送分小仙女□ 提交于 2019-12-13 07:07:36

问题


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.



来源:https://stackoverflow.com/questions/29852972/sending-multiple-emits-inside-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!