Eventemitter and nexttick in nodejs

雨燕双飞 提交于 2019-12-02 16:33:23

问题


I'm confused about 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!

回答1:


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. 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.

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');


来源:https://stackoverflow.com/questions/38140113/eventemitter-and-nexttick-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!