0π
This is expected behaviour of node.js
any synchronous loop will always block the thread and after the loop is complete it will process the other events.
Please refer Event loop for more information but for the highlights:
There are 5 phases
βββββββββββββββββββββββββββββ ββ>β timers β β βββββββββββββββ¬ββββββββββββββ β βββββββββββββββ΄ββββββββββββββ β β pending callbacks β β βββββββββββββββ¬ββββββββββββββ β βββββββββββββββ΄ββββββββββββββ β β idle, prepare β β βββββββββββββββ¬ββββββββββββββ βββββββββββββββββ β βββββββββββββββ΄ββββββββββββββ β incoming: β β β poll β<ββββββ€ connections, β β βββββββββββββββ¬ββββββββββββββ β data, etc. β β βββββββββββββββ΄ββββββββββββββ βββββββββββββββββ β β check β β βββββββββββββββ¬ββββββββββββββ β βββββββββββββββ΄ββββββββββββββ ββββ€ close callbacks β βββββββββββββββββββββββββββββ
Now poll
is where synchronous code is executed and pending callbacks
are where your callbacks are processed. So when the phase moves to poll
it already checked for all the callbacks and async/libuv stuff. So your for loop
is here, Now until it is fully executed it wont go to the next phase of the event loop and return to the pending callbacks
phase.
So after the loop completes it will go to the other phases and will see that there are multiple unservices callbacks are there (your events) and it will process it one by one. Hope you understood the concept.
One thing you can do is, you can fork another process just to serve your events and send the fruits
using process.send
rather than events. Then the process will immediately serve the event handler.