Home > Blockchain >  node.js remove event listener nested inside a event listener
node.js remove event listener nested inside a event listener

Time:11-30

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.

CodePudding user response:

.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);
        });
    });
  • Related