CodePark/ questions / EventEmitter
START PRACTICINGPRACTICE
Backend question · Node.js › EventEmitter

What does this log?

const { EventEmitter } = require("node:events");
const e = new EventEmitter();
e.on("ping", () => console.log("listener"));

console.log("before");
e.emit("ping");
console.log("after");
before listener after

The output is "before listener after".

emit is synchronous. It calls every listener right away, on the same call stack, before it returns. Events are not put in a queue on the event loop. So the listener runs between "before" and "after".

"before after listener" is the tempting wrong answer. It would be right only if events waited for the event loop, and they don't. If a listener needs to delay its work, it must schedule the work itself with
setImmediate or process.nextTick.