跳到内容

理解 process.nextTick()

🌐 Understanding process.nextTick()

当你尝试理解 Node.js 的事件循环时,其中一个重要部分是 process.nextTick()。每当运行时回调 JavaScript 处理某个事件时,我们称之为一个 tick。

🌐 As you try to understand the Node.js event loop, one important part of it is process.nextTick(). Every time the runtime calls back into JavaScript for an event, we call it a tick.

当我们将一个函数传递给 process.nextTick() 时,我们指示引擎在当前操作完成后立即调用该函数,然后再进入事件循环的下一个阶段:

🌐 When we pass a function to process.nextTick(), we instruct the engine to invoke this function immediately after the current operation completes, before moving to the next phase in the event loop:

.(() => {
  // do something
});

事件循环正在忙于处理当前的函数代码。当此操作结束时,JS 引擎会运行在该操作期间传给 nextTick 调用的所有函数。

🌐 The event loop is busy processing the current function code. When this operation ends, the JS engine runs all the functions passed to nextTick calls during that operation.

这是我们可以告诉 JS 引擎异步处理函数(在当前函数之后)的方式,但要尽快处理,而不是将其排队。

🌐 It's the way we can tell the JS engine to process a function asynchronously (after the current function), but as soon as possible, not queue it.

调用 setTimeout(() => {}, 0) 会在下一个事件循环的末尾执行该函数,远比使用 nextTick() 执行晚,后者会优先执行调用,并在下一个事件循环开始之前执行。

🌐 Calling setTimeout(() => {}, 0) will execute the function at the end of next tick, much later than when using nextTick() which prioritizes the call and executes it just before the beginning of the next tick.

当你想确保在下一个事件循环迭代中代码已经执行时,使用 nextTick()

🌐 Use nextTick() when you want to make sure that in the next event loop iteration that code is already executed.

要了解更多关于执行顺序以及事件循环的工作原理,请查看专门的文章

🌐 To learn more about the order of execution and how the event loop works, check out the dedicated article