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

前端 未结 1 1392
灰色年华
灰色年华 2020-12-31 11:31

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

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


        
相关标签:
1条回答
  • 2020-12-31 12:08

    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.

    0 讨论(0)
提交回复
热议问题