简体   繁体   English

Node.js中的Eventemitter和Nexttick

[英]Eventemitter and nexttick in nodejs

I'm confused about Eventemitter. 我对Eventemitter感到困惑。 I write a code but that does not work properly. 我写了一个代码,但是不能正常工作。 Why the below code does not work : 为什么以下代码不起作用:

const EventEmitter = require('events');
const util = require('util');

function MyEmitter() {
  EventEmitter.call(this);
  this.emit('event');
}
util.inherits(MyEmitter, EventEmitter);

const myEmitter = new MyEmitter();
myEmitter.on('event', function() {
  console.log('an event occurred!');
});
// No output!

But the below code works? 但是下面的代码有效吗?

const EventEmitter = require('events');
const util = require('util');

function MyEmitter() {
  EventEmitter.call(this);

  process.nextTick(function () {
    this.emit('event');
  }.bind(this));
}
util.inherits(MyEmitter, EventEmitter);

const myEmitter = new MyEmitter();
myEmitter.on('event', function() {
  console.log('an event occurred!');
});

Output : 输出:

 an event occured!

EventEmitter emits synchronously, which means that in your first example, the event being emitted (from the constructor) is emitted before a listener has been attached. EventEmitter同步发出,这意味着在您的第一个示例中,正在发出的事件(从构造函数发出)是在附加侦听器之前发出的。 Because events aren't queued or "saved", your event listener won't get the message (it simply started listening too late). 因为事件没有排队或“保存”,所以事件监听器不会收到消息(它只是开始监听太晚了)。

In your second example, the event is emitted from the constructor in the next cycle of the event loop (asynchronously). 在第二个示例中,事件是在事件循环的下一个周期(异步)中从构造函数发出的。 At that point, the code that adds the listener to myEmitter has already run, so at the time the event is being emitted the listener will receive it. 到那时,将侦听器添加到myEmitter的代码已经运行,因此在发出事件时,侦听器将接收到它。

It's similar to this: 与此类似:

// synchronously: 'A' is logged before 'B'
console.log('A');
console.log('B');

// asynchronously: 'B' is logged before 'A'
process.nextTick(function() { console.log('A') });
console.log('B');

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

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