Sushant Keni
Sushant Keni

Reputation: 93

Events & Event Emitter in Node.js

So I've attached two events if someone screams, they are called synchronously, why so?

const events = require('events'); 

const eventEmitter = new events.EventEmitter();

eventEmitter.on('scream', function() {
    console.log("Screaming");
});

eventEmitter.on('scream', function(name) {
    console.log(name+" is screaming");
});

eventEmitter.emit('scream', 'Bob');

O/P: Screaming

Bob is screaming

Upvotes: 5

Views: 2189

Answers (2)

Mahdi Aryayi
Mahdi Aryayi

Reputation: 1120

Because the Event loop fetches events from Event Queue and sends them to call stack one by one.

And Event Queue is FIFO (First-In-First-Out)

Upvotes: 1

Shubham Verma
Shubham Verma

Reputation: 9971

Because in nodejs, The event loop is single threaded and pick one event at a time and treat those events independently.

In your case, there are two event handler with the same name, so when event loop gets the eventEmitter.emit('scream', 'Bob') it sends the particular event handler. When first event handler done with it, Now it goes to the second handler because with the same name. It follow the FIFO but if you use emitter.prependListener(eventName, listener) then it will be executed first the FIFO.

You should know, if you want to call only one time then you should use eventEmitter.once('scream') It will be called only one time.

eventEmitter.once('scream', function() {
    console.log("Screaming");
});

eventEmitter.emit('scream', 'Bob');
eventEmitter.emit('scream', 'Bob');
eventEmitter.emit('scream', 'Bob');

Output: Screaming // Only one time.

Upvotes: 1

Related Questions