J
J
jenya77712018-04-01 14:13:41
Node.js
jenya7771, 2018-04-01 14:13:41

How to remove a specific socket.io listener?

Hello, there is such a function

exports.list = () => {

  return new Promise((resolve, reject) => {

    try {

      if (conect) {

        const hash = crypto.randomBytes(30).toString('hex')
        
        socket
        .emit('list', JSON.stringify({
          auth: key,
          hash: hash
        }))
        .on('list', (data) => {

          data = JSON.parse(data) 

          if (data.hash === hash) {

            resolve(data.list)
          }
        });
      } else {

        reject(new Error('Disconnect to socket API'))
      }
    } catch (error) {

      reject(error)
    }	
  })
}

And it is called very often, and as I understand it, with each call, I create a list listener, and after I receive a response, it is not deleted and because of this there is a huge load on the server, today I already asked a question .
As I understand it, after receiving a response from the listener, I need to delete it, but how can I delete a specific List listener, and not all?
I use Socket to receive data (as an API), and I don’t know how to do the same with one listener, can anyone do something similar, and is there a way out of this situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladlen Hellsite, 2018-04-01
@jenya7771

There are two options:
1. Put the listener globally and don't remove it. (More correct)
2. Use instead of .on(), .once(). It creates a listener and after one event it will be removed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question