Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
Is there a way to put socket.io events into functions?

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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

Update: I have kinda found the OOP solution for this (it is not the best):

class ConnectionHandler {

init() {
  this.listenForConnections();
}

listenForConnections() {
 io.on('connection', (socket) =>{
        //do stuff
        this.newConnection = true;
        this.update();
 });
}

// the update method contains all the logical decisions of a class
update() {
   if(this.isThereANewConnection()) {
    //add connection to list.. or handle the rest of the logic
  }
  //render screen
}

isThereANewConnection() {
   if(this.newConnection) {
    this.newConnection = false;
    return true;
  }
 return false;
}

}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda