[英]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.在这里,我使用消息事件发射器将消息内容发送回已解析的 promise,并且我使用了 client.off。 However even after this, I still get the 11 event listeners attached to client warning.但是,即使在此之后,我仍然将 11 个事件侦听器附加到客户端警告。 Where am I going wrong?我哪里错了? And yes this is the only variable that actually attaches the event emitter.是的,这是唯一实际附加事件发射器的变量。
.off()
requires that you pass it the identical function reference (not a different function that is an identical copy). .off()
要求您将相同的 function 引用传递给它(不是不同的 function 是相同的副本)。 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()
:因此,您可以通过使第一个消息处理程序成为单独的本地 function 来修复您的代码,然后您可以在.on()
.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.仅供参考,您也可以使用.once()
,它会自动为您处理删除。
const globalInput = new Promise(resolve => {
client.once('message', msg => {
resolve(msg.content);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.