With socketio is it possible to use async with socket.on

纵饮孤独 提交于 2020-02-01 05:11:04

问题


Is it possible to do something like that with socket io :

socket.on('event.here', async (data) => {
     const result:any = await webservice();
}

I'm not quite sure how to do it ?


回答1:


Yes you can do it, but it depends on what you want to do. If you want to be able to await for some async operation inside callback than you are all set. But if you want for the next event to not fire before handling of previous one was finished than it won't work that way.

Here is a little simulation:

let socket = {
  listeners: [],
  on: function(name, callback) {
    if (!this.listeners[name]) {
      this.listeners[name] = [];
    }
    this.listeners[name].push(callback);
  },
  emit: function(name, data) {
    if (this.listeners[name]) {
        this.callListeners(this.listeners[name], data);
    }
  },
  callListeners: function(listeners, data) {
    listeners.shift()(data);
      if (listeners.length) {
        this.callListeners(listeners, data);
      }
  }
}

function returnsPromise() {
    return new Promise((resolve) => {
    setTimeout(() => {
        resolve();
    }, 1000);
  })
}

socket.on('event.here', async (data) => {
     const result = await returnsPromise();
     console.log('after await');
});

socket.on('event.here', async (data) => {
     const result = await returnsPromise();
     console.log('after await1');
});

socket.emit('event.here', {});

You can play with it here to get a feeling, in fact SocketIO has nothing to do with it being able to work.



来源:https://stackoverflow.com/questions/47035243/with-socketio-is-it-possible-to-use-async-with-socket-on

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