Reputation: 3309
I was reading this article from the node.js website. At some point, they comment the following snippet :
const server = net.createServer(() => {}).listen(8080);
server.on('listening', () => {});
When only a port is passed, the port is bound immediately. So, the 'listening' callback could be called immediately. The problem is that the .on('listening') callback will not have been set by that time.
To get around this, the 'listening' event is queued in a nextTick() to allow the script to run to completion. This allows the user to set any event handlers they want.
However, browsing the node.js source code, it doesn't seem to be the case.
The listening
doesn't seem to be wrapped in a process.nextTick()
call, whereas explicit nextTick calls do exist at other places in the code.
What am I missing ?
Upvotes: 2
Views: 430
Reputation: 138277
Actually the event is triggered here:
defaultTriggerAsyncIdScope(this[async_id_symbol],
process.nextTick,
emitListeningNT,
this);
And that basically just calls process.nextTick
with the arguments emitListeningNT, this
. So after one tick this is called:
function emitListeningNT(self) {
// ensure handle hasn't closed
if (self._handle)
self.emit('listening');
}
Which then trigeers the event. So the event is triggered one tick after the server started.
Upvotes: 2