metis metis - 5 months ago 15
Node.js Question

Eventemitter and nexttick in nodejs

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!

Answer

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