I have a question regarding the order of operations in the below code snippet,
const EventEmitter = require("events").EventEmitter;
const messenger = new EventEmitter();
process.nextTick(() => {
console.log("Next Tick");
});
messenger.on("message", (msg) => {
console.log("Message: ", msg);
});
messenger.emit("message", "Hello");
console.log("The end!");
I was expecting the event handler code to be executed after all the synchronous code has already executed and ideally after the process.nextTick()
as it was "registered" before. My Expectations was:
The end!
Next Tick
Message: Hello
However the output was
Message: Hello
The end!
Next Tick
Can someone please help me with this?
>Solution :
An EventEmitter is like a "function call assistant". The emitting environment need not know what handlers are associated with the message types on an emitter instance. So
emitter.emit("something", "hi there");
basically means, "please call all the handler functions associated with event ‘something’". The emitter immediately, synchronously, and not in a way involving the event loop, will make those function calls one after another.
Thus the emitter pattern looks like something that would be asynchronous, but it is not. It’s like having an array filled with function references, and then
array.forEach(fn => fn());
(not exactly, but kind-of).