With socketio is it possible to use async with soc

2019-07-11 18: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.