Promise 执行跟踪


默认情况下,promise 执行不会分配 asyncIds,因为 V8 提供的 promise introspection API 相对 昂贵。这意味着使用 promise 或 async/await 的程序 默认情况下不会为 promise 回调上下文获得正确的执行 ID 和触发 ID。

import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';

Promise.resolve(1729).then(() => {
  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
});
// 产生:
// eid 1 tid 0const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');

Promise.resolve(1729).then(() => {
  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
});
// 产生:
// eid 1 tid 0

注意,then() 回调声称它在外部作用域的上下文中执行, 尽管其中涉及异步跳转。此外, triggerAsyncId 值为 0,这意味着我们缺少有关 导致(触发)then() 回调被执行的资源的信息。

通过 async_hooks.createHook 安装 async hooks 会启用 promise 执行跟踪:

import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
Promise.resolve(1729).then(() => {
  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
});
// 产生:
// eid 7 tid 6const { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');

createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
Promise.resolve(1729).then(() => {
  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
});
// 产生:
// eid 7 tid 6

在此示例中,添加任何实际的钩子函数都会启用对 promise 的跟踪。上面的示例中有两个 promise;由 Promise.resolve() 创建的 promise 和调用 then() 返回的 promise。在上面的示例中,第一个 promise 获得了 asyncId 6, 后者获得了 asyncId 7。在 then() 回调执行期间,我们在 asyncId 为 7 的 promise 上下文中执行。该 promise 由 异步资源 6 触发。

promise 的另一个微妙之处是 before 和 after 回调 只在链式 promise 上运行。这意味着不是由 then()/catch() 创建的 promise 不会触发 before 和 after 回调。更多细节 请参阅 V8 PromiseHooks API 的细节。