gpt4 book ai didi

javascript - Node.js process.nextTick & net的监听事件

转载 作者:行者123 更新时间:2023-11-29 20:55:38 25 4
gpt4 key购买 nike

我正在阅读 this article来自 node.js 网站。在某些时候,他们评论了以下片段:

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.

但是,浏览node.js source code ,似乎并非如此。

listening 似乎没有包含在 process.nextTick() 调用中,而显式 nextTick 调用确实存在于代码的其他位置。

我错过了什么?

最佳答案

其实事件是在这里触发的:

 defaultTriggerAsyncIdScope(this[async_id_symbol],
process.nextTick,
emitListeningNT,
this);

这基本上只是使用参数 emitListeningNT, this 调用 process.nextTick。所以在一次滴答之后,这被称为:

 function emitListeningNT(self) {
// ensure handle hasn't closed
if (self._handle)
self.emit('listening');
}

然后触发事件。所以事件在服务器启动后的一个 tick 被触发。

关于javascript - Node.js process.nextTick & net的监听事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49493154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com