Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 760
An-droid Avatar asked Oct 31 '17 12:10

An-droid


People also ask

Is Socket.IO synchronous or asynchronous?

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.

Is Socket.IO a WebSocket?

Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet.

Is Socket.IO synchronous?

Show activity on this post. Yes, all NodeJS I/O is (or should be) asynchronous.

Is Socket.IO a WebRTC?

Socket.IO P2P provides an easy and reliable way to setup a WebRTC connection between peers and communicate using the socket. io-protocol.


1 Answers

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.

like image 161
guramidev Avatar answered Sep 20 '22 07:09

guramidev