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

106
Visualizações
node.js remove event listener nested inside a event listener
const globalInput = new Promise(resolve => {
            function callback(msg) {
                client.off('message', (msg) => callback(msg));
                resolve(msg.content);
            }
            client.on('message', (msg) => callback(msg));
        });

Here I've used the message event emitter to send the message contents back in a resolved promise, and I've used client.off. However even after this, I still get the 11 event listeners attached to client warning. Where am I going wrong? And yes this is the only variable that actually attaches the event emitter.

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

0

.off() requires that you pass it the identical function reference (not a different function that is an identical copy). So, you can fix your code by making the first message handler be a separate local function that you can then refer to in both .on() and .off():

    const globalInput = new Promise(resolve => {
        function handler(msg) {
             client.off('message', handler);
             resolve(msg.content);
        }
        client.on('message', handler);
    });

FYI, you can also use .once() and it will handle the removal for you automatically.

    const globalInput = new Promise(resolve => {
        client.once('message', msg => {
            resolve(msg.content);
        });
    });
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