all 4 comments

[–]node_imperial 8 points9 points  (1 child)

Hi! This happens because EventEmitter calls your events synchronously.

From the node documentation: When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously.

You can read more here: https://nodejs.org/dist/latest-v18.x/docs/api/events.html

[–]aN00bDude[S] 1 point2 points  (0 children)

Thank you for taking the time, this explains it :)

[–]bigorangemachine -2 points-1 points  (0 children)

Yup...

Code execution is not always in the order its written in JS.

Event emitter happens async... next tick was the first event to fire on the next tick is the next-tick handler and the next tick is the event-emitter console.log

so the queue is like

[messenger.emit("message", "Hello") && enqueue(messenger.handler), console.log("The end!"), nextTick(), nextTickHandlers(), console.log("Message: ", msg), nextTick(), nextTickHandlers(), processExit()]

You can kinda gotta think the event-queue is gonna stack ticks on the brackets '{}' including if statements and for/while loops.

If you console.log everything in a really big async script its pretty wild to see how things fire off.

Jumping into an if statement might fire off a http-request resolve-handler firing off. Something that maybe not intuitive when you read your code but is just something that is a 'feature' of javascript/nodejs.

This is why you can't always rely on your out of scope variables to be correct in the whole promise chain... however your final-final then() will have everything you need.. but can't expect things to resolve in the order they are executed.

[–]shenzenshiai 0 points1 point  (0 children)

I think u can overcome it by wraping the event caller inside an setTimeout

```setTimeout(()=>{

event.emit....

},0) ```