typescript 使用 socketio 是否可以将异步与 socket.on 一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47035243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
With socketio is it possible to use async with socket.on
提问by An-droid
Is it possible to do something like that with socket io :
是否可以使用 socket io 做类似的事情:
socket.on('event.here', async (data) => {
const result:any = await webservice();
}
I'm not quite sure how to do it ?
我不太确定该怎么做?
回答by guramidev
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 hereto get a feeling, in fact SocketIO has nothing to do with it being able to work.