Home > Mobile >  Is there a way to put socket.io events into functions?
Is there a way to put socket.io events into functions?

Time:01-03

I wanna encapsulate socket.io events into functions to make it more readable for my project, here is an example. I am trying to put this:

io.on('connection', (socket) =>{
            //code
});

Into something like this:

function isThereANewConnection() {
 io.on('connection', (socket) =>{
        //..return true?
 });
}

function update() {
   if(isThereANewConnection()) {
    //do something with the socket data..
  }
}

I cannot seem to figure out how i could implement this since i cannot return something from the function. Does anyone know how to do this?

CodePudding user response:

You haven't really explained what you're trying to accomplish by putting "events into functions" so it's hard to know precisely what you want it to look like.

At it's heart, nodejs is an event driven environment. As such, you register event listeners and they call you when there's an event. That's the structure of the socket.io connection event.

If you don't want everything inline such as this:

io.on('connection', (socket) =>{
            //code
});

You can put the event listener callback into a function itself such as:

io.on('connection', onConnection);

Then, somewhere else (either in the same module or imported into this module), you would define the onConnection function.

function onConnection(socket) {
    // put your code here to handle incoming socket.io connections
    socket.on('someMsg', someData => {
        // handle incoming message here
    });
}

Note: inline callback functions (of the type you seem to be asking to avoid) are very common in nodejs programming. One of the reasons for using them is that when they are inline, they have available to them all the variables from the parent scope (without having to pass them all as arguments) and there are times this is very useful. So, it might be a style that you will find useful rather than avoiding.

CodePudding user response:

I don't think this is going to structure your code in a way that is more readable and useful to you. But if you did want this, you could use async/await.

async function getNewConnection() {
  return await new Promise((resolve, reject) => {
    io.on('connection', resolve);
  });
}

Then in your other code:

const socket = await getNewConnection();

Really though, for this connection handler you should stick with the callback pattern. It keeps things simple for you. Run your updates when the connection comes in, and not the other way around.

  • Related