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 ?
JS, Socket.IO enables asynchronous, two-way communication between the server and the client. This means that the server can send messages to the client without the client having to ask first, as is the case with AJAX.
Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet.
Show activity on this post. Yes, all NodeJS I/O is (or should be) asynchronous.
Socket.IO P2P provides an easy and reliable way to setup a WebRTC connection between peers and communicate using the socket. io-protocol.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With