javascript - Node.js事件循环理解(附图)

标签 javascript node.js event-loop

我已阅读 thisthis , 观看 this ...

我已经制作了一个图表来说明我是如何理解它的:

enter image description here

  • Javascript 回调(函数)可以存在于 current queuecheck queueclose callbacks queuetimers queueI/O 回调队列
  • Js 代码仅从 当前队列 一次执行一个函数(任务/作业)。
  • 此时执行的Js代码可以将微任务(作业)添加到当前队列后自己执行,宏任务(任务)添加到检查队列。它只能通过请求 API 来将任务添加到其他队列中。
  • 空闲,准备阶段用于一些内部 Node js业务(可能像垃圾回收)。
  • Poll 阶段从线程池中轮询线程,并使用适当的回调填充队列。
  • Idle、preparepoll 阶段没有与之关联的 js 回调队列。
  • (四个)线程池中的线程都是相同的,没有特化。
  • 事件循环从每个队列中一个接一个地执行任务,直到它为空,然后移动到下一个队列。
  • 队列中的任务没有与之关联的任何作业(微服务)。作业仅在执行任务或其他作业期间创建,并且仅存在于当前任务队列中。

这种理解是对的还是我遗漏了什么?

可以找到带有图表的 MS Power Point .pptx 文件 here .

最佳答案

图表看起来确实很复杂。在这种情况下,我发现一个国王类比非常完美,可以对事件循环的工作原理有一个灰度级的理解。

Imagine the code you want to run is a king and node is the army of servants.

The day starts by one servant waking up the king and asking him if he needs anything. The king gives the servant a list of tasks and goes back to sleep a little longer. The servant now distributes those tasks among his colleagues and they get to work.

Once a servant finishes a task, he lines up outside the kings quarter to report. The king lets one servant in at a time, and listens to things he reports. Sometimes the king will give the servant more tasks on the way out.

Life is good, for the king's servants carry out all of his tasks in parallel, but only report with one result at a time, so the king can focus.

这里的王者是主 Node 进程。这就是 nodejs 被称为单线程但异步的方式。

关于javascript - Node.js事件循环理解(附图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45566463/

相关文章:

node.js - Node-Webkit 和 AngularJS 包应用程序 : require not defined

JavaScript 事件循环乱序执行

node.js - Node - 设置每个异步回调的最大时间

swift - Steam 3 : Eventloop bug detected when using wait()

javascript - 如何在 WP 自定义页面中包含自定义 JS 文件

在 aws ubuntu 服务器上运行 server.listen 时出现 node.js 错误

javascript - 如何选择第一列以在每一列中添加升序数字?

javascript - 从 Node.js 连接到谷歌搜索控制台 API

javascript - anchor 标签和图像映射

javascript - 使用 bxslider 时图像上没有箭头