简体   繁体   English

Nodejs事件发射器程序中语句的执行顺序

[英]Order of execution of statements in Nodejs event emitter program

I tried the following NodeJs example:我尝试了以下 NodeJs 示例:

const EventEmitter = require('events');
var eventEmitter = new EventEmitter();

var fun1 = (msg) => {
    console.log("Message from fun1: " + msg);
};
var fun2 = (msg) => {
    console.log("Message from fun2: " + msg);
};

eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun2);

eventEmitter.removeListener('myEvent', fun1);
eventEmitter.emit('myEvent', "Event occurred");
console.log(eventEmitter.listenerCount('myEvent'));
eventEmitter.removeAllListeners('myEvent');
console.log(eventEmitter.listenerCount('myEvent'));

eventEmitter.emit('myEvent', "Event occurred");

Output is: Output 是:

Message from fun1: Event occurred来自 fun1 的消息:事件发生

Message from fun2: Event occurred来自 fun2 的消息:事件发生

2 2

0 0

Please help me in understanding the output, as according to my expectation the line 'Message from fun2: Event occurred' shouldn't have been printed, as I've called removeAllListeners before it.请帮助我理解 output,因为根据我的预期,不应该打印“来自 fun2 的消息:事件发生”行,因为我在它之前调用了 removeAllListeners。 And, Event emitter functions are called synchronously.并且,事件发射器函数被同步调用。 Also, if Event emitter functions are really executed in synchronous manner, why are all the console logs getting printed at the very end?另外,如果事件发射器功能真的以同步方式执行,为什么所有控制台日志都在最后打印?

Nodejs docs say Nodejs 文档说

If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.如果任何单个侦听器已多次添加到指定 eventName 的侦听器数组,则必须多次调用 removeListener() 以删除每个实例。

That's why it's still printing count as 2. Because there still are two listeners active for event "myevent" "fun1" and "fun2".这就是为什么它仍然打印计数为 2。因为对于事件“myevent”“fun1”和“fun2”仍有两个活动的侦听器。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM