使用 socketio 是否可以将异步与 socket.on 一起使用 [英] With socketio is it possible to use async with socket.on

查看:69
本文介绍了使用 socketio 是否可以将异步与 socket.on 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 socket io 做类似的事情:

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

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

我不太确定该怎么做?

推荐答案

是的,你可以做到,但这取决于你想做什么.如果您希望能够在回调中等待一些异步操作,那么您已经做好了准备.但是,如果您希望在处理完前一个事件之前不触发下一个事件,那么它不会以这种方式工作.

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.

这里是一个小模拟:

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', {});

你可以玩玩这里来感受一下,其实SocketIO与它无关它能够工作.

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

这篇关于使用 socketio 是否可以将异步与 socket.on 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆