Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does event handler code execute before the synchronous code has been run?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading