skip to Main Content

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?

2

Answers


  1. Events are not async per se. They can be sync if you emit and handle they in a sync way.

    From the Node.js docs:

    "The EventEmitter calls all listeners synchronously in the order in which they were registered. This ensures the proper sequencing of events and helps avoid race conditions and logic errors. When appropriate, listener functions can switch to an asynchronous mode of operation using the setImmediate() or process.nextTick() methods".

    (See https://nodejs.org/api/events.html#asynchronous-vs-synchronous)

    Login or Signup to reply.
  2. 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search