Hidden threads in Javascript/Node that never execute user code: is it possible, and if so could it lead to an arcane possibility for a race condition?

No, this cannot happen.

Yes, there are indeed “hidden” background threads that do the work for asychronous methods, but those don’t call callbacks. All execution of javascript does happen on the same thread, synchronously, sequentially. That data event callback will always be executed asynchronously, that is, after the current script/function ran to completion.

While there could indeed already arrive packets from the network before the callback is created and attached to the event emitter, the callback that listens for packets on the lowest level is always created before the request is sent – it is an argument to the native “makeRequest” method, and is available to be called right from the beginning. So when a packet does arrive before the current script (still being occupied by constructing event emitters and attaching handlers) has finished, this event is queued up, and the callback will only be executed after the event loop is ready – on the next turn. By then, the data event callback is certainly created and attached.

Leave a Comment