I just started exploring Node JS event-driven architecture and event loop, What I understand is that Event emitters enter into the Event Loop which should be asynchronous but when I execute below I see event emitters are logged first and then top-level code.
const EventEmitter = require("events");
const myEmitter = new EventEmitter();
myEmitter.on('newSale', () => {
console.log('New sale received');
})
myEmitter.on('newSale', (saleValue) => {
console.log('New sale received from John Doe', + saleValue);
})
myEmitter.emit('newSale', 29);
console.log('Top level code');
My assumption and expectation is that, If event emitters enter into the event loop then top-level code should be executed and then event loop code (in our case event emitters) should be executed.
As per my expectation below should be the order of the logs.
- Top level code
- New sale received
- New sale received from John Doe 29
But below is the actual logs which are getting printed.
- New sale received
- New sale received from John Doe 29
- Top level code
Any help in understanding the above is appreciated.
I am not sure whether you misunderstood or the blogs you referred to are misleading. But
Event-LoopandEventEmitterare completely different things that cause a lot of misunderstandings because of the wordEvent...From the Node Documentation: https://nodejs.org/api/events.html
When the
EventEmitterobject emits an event, all of the functions attached to that specific event are called synchronously. To make it Asynchronous you have to usesetImmediate(),setTimeout()process.nextTick()approaches.More Info: https://nodejs.org/api/events.html#asynchronous-vs-synchronous
The above script will print the output as you expected.
Here the
EventEmitterdoes not automatically enter into theEventLoop. By invokingsetImmediate()we tell the Node to execute it Asynchronously.