🌐 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 schedule it to run immediately after the current call stack completes, before the event loop continues and before any other queued tasks or phases are processed:
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) 会为未来的事件循环迭代安排回调,比使用 process.nextTick() 要晚得多,后者会在事件循环继续之前执行。
🌐 Calling setTimeout(() => {}, 0) schedules the callback for a future event loop iteration, much later than when using process.nextTick(), which executes before the event loop continues.
当你想确保在下一个事件循环迭代中代码已经执行时,使用 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