了解 process.nextTick()

¥Understanding process.nextTick()

当你尝试了解 Node.js 事件循环时,其中一个重要部分是 process.nextTick()。每次事件循环完成一次完整的行程时,我们都将其称为一个勾号。

¥As you try to understand the Node.js event loop, one important part of it is process.nextTick(). Every time the event loop takes a full trip, we call it a tick.

当我们将一个函数传递给 process.nextTick() 时,我们会指示引擎在当前操作结束时(下一个事件循环开始之前)调用此函数:

¥When we pass a function to process.nextTick(), we instruct the engine to invoke this function at the end of the current operation, before the next event loop tick starts:

process.nextTick(() => {
  // 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) 将在下一个 tick 结束时执行该函数,比使用 nextTick() 时晚得多,nextTick() 优先调用并在下一个 tick 开始之前执行它。

¥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.

事件顺序示例:

¥An Example of the order of events:

console.log('Hello => number 1');

setImmediate(() => {
  console.log('Running before the timeout => number 3');
});

setTimeout(() => {
  console.log('The timeout running last => number 4');
}, 0);

process.nextTick(() => {
  console.log('Running at next tick => number 2');
});

示例输出:

¥Example output:

Hello => number 1
Running at next tick => number 2
Running before the timeout => number 3
The timeout running last => number 4

每次运行的确切输出可能不同。

¥The exact output may differ from run to run.