Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!