nextTick中为什么需要async_hooks
发布于 7 年前 作者 xtx1130 3038 次浏览 来自 分享

最近被一个地方搞得很头疼,就是nextTick中为什么需要async_hooks:

// ./lib/internal/process/next_tick.js
function _tickCallback() {
    let tock;
    do {
      while (tock = shift()) {
        const asyncId = tock[async_id_symbol];
        emitBefore(asyncId, tock[trigger_async_id_symbol]);
        if (destroyHooksExist())
          emitDestroy(asyncId);
        const callback = tock.callback;
        if (tock.args === undefined)
          callback();
        else
          Reflect.apply(callback, undefined, tock.args);
        emitAfter(asyncId);
      }
      runMicrotasks();
    } while (head.top !== head.bottom || emitPromiseRejectionWarnings());
    tickInfo[kHasPromiseRejections] = 0;
  }

之前做过nextTick的源码分析,当时并没有去深入探究。最近抽时间在async_hook的文档中找到了答案:

The TCPSERVERWRAP is not part of this graph, even though it was the reason for console.log() being called. This is because binding to a port without a hostname is a synchronous operation, but to maintain a completely asynchronous API the user’s callback is placed in a process.nextTick().

于是下决心把async_hook的文档翻译的一遍,还是有不少收获的。如果大家有兴趣的话,可以读一读,链接在此。有问题的地方可以直接提pr,我会尽快处理,如果对文档有异议却又不能确定,请在这个issue下提出。

回到顶部