Async Hooks#

稳定性: 1 - 实验性。 如果可以,请迁移离开此 API。 我们不建议使用 createHookAsyncHookexecutionAsyncResource API,因为它们存在可用性问题、安全风险和性能影响。 异步上下文跟踪用例最好由稳定的 AsyncLocalStorage API 提供。 如果您有 createHookAsyncHookexecutionAsyncResource 的用例,超出 AsyncLocalStorage 解决的上下文跟踪需求或 诊断通道 当前提供诊断数据,请在 https://github.com/nodejs/node/issues 上打开一个 issue,描述您的用例,以便我们可以创建更多以目标为中心的 API。

源代码: lib/async_hooks.js

我们强烈建议不要使用 async_hooks API。 可以涵盖其大多数用例的其他 API 包括

node:async_hooks 模块提供了一个 API 来跟踪异步资源。 可以使用以下方式访问它

import async_hooks from 'node:async_hooks';const async_hooks = require('node:async_hooks');

术语#

异步资源表示具有关联回调的对象。 此回调可能会被多次调用,例如 net.createServer() 中的 'connection' 事件,或者像 fs.open() 中一样只被调用一次。 资源也可能在回调被调用之前关闭。 AsyncHook 不会明确区分这些不同的情况,而是将它们表示为资源抽象概念。

如果使用 Worker,则每个线程都有一个独立的 async_hooks 接口,并且每个线程将使用一组新的异步 ID。

概述#

以下是公共 API 的简单概述。

import async_hooks from 'node:async_hooks';

// Return the ID of the current execution context.
const eid = async_hooks.executionAsyncId();

// Return the ID of the handle responsible for triggering the callback of the
// current execution scope to call.
const tid = async_hooks.triggerAsyncId();

// Create a new AsyncHook instance. All of these callbacks are optional.
const asyncHook =
    async_hooks.createHook({ init, before, after, destroy, promiseResolve });

// Allow callbacks of this AsyncHook instance to call. This is not an implicit
// action after running the constructor, and must be explicitly run to begin
// executing callbacks.
asyncHook.enable();

// Disable listening for new asynchronous events.
asyncHook.disable();

//
// The following are the callbacks that can be passed to createHook().
//

// init() is called during object construction. The resource may not have
// completed construction when this callback runs. Therefore, all fields of the
// resource referenced by "asyncId" may not have been populated.
function init(asyncId, type, triggerAsyncId, resource) { }

// before() is called just before the resource's callback is called. It can be
// called 0-N times for handles (such as TCPWrap), and will be called exactly 1
// time for requests (such as FSReqCallback).
function before(asyncId) { }

// after() is called just after the resource's callback has finished.
function after(asyncId) { }

// destroy() is called when the resource is destroyed.
function destroy(asyncId) { }

// promiseResolve() is called only for promise resources, when the
// resolve() function passed to the Promise constructor is invoked
// (either directly or through other means of resolving a promise).
function promiseResolve(asyncId) { }const async_hooks = require('node:async_hooks');

// Return the ID of the current execution context.
const eid = async_hooks.executionAsyncId();

// Return the ID of the handle responsible for triggering the callback of the
// current execution scope to call.
const tid = async_hooks.triggerAsyncId();

// Create a new AsyncHook instance. All of these callbacks are optional.
const asyncHook =
    async_hooks.createHook({ init, before, after, destroy, promiseResolve });

// Allow callbacks of this AsyncHook instance to call. This is not an implicit
// action after running the constructor, and must be explicitly run to begin
// executing callbacks.
asyncHook.enable();

// Disable listening for new asynchronous events.
asyncHook.disable();

//
// The following are the callbacks that can be passed to createHook().
//

// init() is called during object construction. The resource may not have
// completed construction when this callback runs. Therefore, all fields of the
// resource referenced by "asyncId" may not have been populated.
function init(asyncId, type, triggerAsyncId, resource) { }

// before() is called just before the resource's callback is called. It can be
// called 0-N times for handles (such as TCPWrap), and will be called exactly 1
// time for requests (such as FSReqCallback).
function before(asyncId) { }

// after() is called just after the resource's callback has finished.
function after(asyncId) { }

// destroy() is called when the resource is destroyed.
function destroy(asyncId) { }

// promiseResolve() is called only for promise resources, when the
// resolve() function passed to the Promise constructor is invoked
// (either directly or through other means of resolving a promise).
function promiseResolve(asyncId) { }

async_hooks.createHook(callbacks)#

注册函数以便为每个异步操作的不同生命周期事件调用。

在资源的生命周期中,会为相应的异步事件调用回调 init()/before()/after()/destroy()

所有回调都是可选的。 例如,如果只需要跟踪资源清理,则只需要传递 destroy 回调。 可以传递给 callbacks 的所有函数的具体细节都在 钩子回调 部分中。

import { createHook } from 'node:async_hooks';

const asyncHook = createHook({
  init(asyncId, type, triggerAsyncId, resource) { },
  destroy(asyncId) { },
});const async_hooks = require('node:async_hooks');

const asyncHook = async_hooks.createHook({
  init(asyncId, type, triggerAsyncId, resource) { },
  destroy(asyncId) { },
});

这些回调将通过原型链继承

class MyAsyncCallbacks {
  init(asyncId, type, triggerAsyncId, resource) { }
  destroy(asyncId) {}
}

class MyAddedCallbacks extends MyAsyncCallbacks {
  before(asyncId) { }
  after(asyncId) { }
}

const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); 

由于 promise 是异步资源,其生命周期通过异步钩子机制跟踪,因此 init()before()after()destroy() 回调*不得*是返回 promise 的异步函数。

错误处理#

如果任何 AsyncHook 回调抛出错误,应用程序将打印堆栈跟踪并退出。 退出路径确实遵循未捕获异常的路径,但是所有 'uncaughtException' 侦听器都将被移除,从而强制进程退出。 除非使用 --abort-on-uncaught-exception 运行应用程序,否则 'exit' 回调仍将被调用,在这种情况下,将打印堆栈跟踪,并且应用程序退出,留下核心文件。

这种错误处理行为的原因是这些回调在对象生命周期中潜在的易失点运行,例如在类构造和销毁期间。 因此,认为有必要快速关闭进程,以防止将来发生意外中止。 如果执行全面的分析以确保异常可以遵循正常的控制流而没有意外的副作用,则将来可能会对此进行更改。

AsyncHook 回调中打印#

由于打印到控制台是一个异步操作,因此 console.log() 将导致调用 AsyncHook 回调。 在 AsyncHook 回调函数中使用 console.log() 或类似的异步操作将导致无限递归。 调试时一个简单的解决方案是使用同步日志记录操作,例如 fs.writeFileSync(file, msg, flag)。 这将打印到文件,并且不会递归调用 AsyncHook,因为它是一个同步操作。

import { writeFileSync } from 'node:fs';
import { format } from 'node:util';

function debug(...args) {
  // Use a function like this one when debugging inside an AsyncHook callback
  writeFileSync('log.out', `${format(...args)}\n`, { flag: 'a' });
}const fs = require('node:fs');
const util = require('node:util');

function debug(...args) {
  // Use a function like this one when debugging inside an AsyncHook callback
  fs.writeFileSync('log.out', `${util.format(...args)}\n`, { flag: 'a' });
}

如果日志记录需要异步操作,则可以使用 AsyncHook 本身提供的信息来跟踪导致异步操作的原因。 然后,当日志记录本身导致调用 AsyncHook 回调时,应跳过日志记录。 通过这样做,否则的无限递归被打破。

类: AsyncHook#

AsyncHook 公开了一个用于跟踪异步操作的生命周期事件的接口。

asyncHook.enable()#

启用给定 AsyncHook 实例的回调。 如果没有提供回调,则启用是一个空操作。

默认情况下,AsyncHook 实例已禁用。 如果应在创建后立即启用 AsyncHook 实例,则可以使用以下模式。

import { createHook } from 'node:async_hooks';

const hook = createHook(callbacks).enable();const async_hooks = require('node:async_hooks');

const hook = async_hooks.createHook(callbacks).enable();

asyncHook.disable()#

从要执行的 AsyncHook 回调的全局池中禁用给定 AsyncHook 实例的回调。 钩子一旦被禁用,在启用之前将不会再次被调用。

为了 API 的一致性,disable() 也会返回 AsyncHook 实例。

钩子回调#

异步事件生命周期中的关键事件已分为四个区域:实例化、在调用回调之前/之后以及销毁实例时。

init(asyncId, type, triggerAsyncId, resource)#
  • asyncId <number> 异步资源的唯一 ID。
  • type <string> 异步资源的类型。
  • triggerAsyncId <number> 此异步资源在其执行上下文中创建的异步资源的唯一 ID。
  • resource <Object> 指向代表异步操作的资源的引用,需要在销毁期间释放。

当构造一个可能发出异步事件的类时调用。 这并不意味着实例必须在调用 destroy 之前调用 before/after,而只是存在这种可能性。

可以通过执行诸如打开一个资源,然后在可以使用该资源之前将其关闭之类的操作来观察此行为。 以下代码段演示了这一点。

import { createServer } from 'node:net';

createServer().listen(function() { this.close(); });
// OR
clearTimeout(setTimeout(() => {}, 10));require('node:net').createServer().listen(function() { this.close(); });
// OR
clearTimeout(setTimeout(() => {}, 10));

每个新资源都分配一个 ID,该 ID 在当前 Node.js 实例的范围内是唯一的。

type#

type 是一个字符串,用于标识导致调用 init 的资源类型。 通常,它将对应于资源构造函数的名称。

Node.js 本身创建的资源的 type 可以在任何 Node.js 版本中更改。 有效值包括 TLSWRAPTCPWRAPTCPSERVERWRAPGETADDRINFOREQWRAPFSREQCALLBACKMicrotaskTimeout。 检查所使用的 Node.js 版本的源代码以获取完整列表。

此外,AsyncResource 的用户可以独立于 Node.js 本身创建异步资源。

还有 PROMISE 资源类型,用于跟踪 Promise 实例以及它们安排的异步工作。

使用公共嵌入器 API 时,用户可以定义自己的 type

可能存在类型名称冲突。 鼓励嵌入器使用唯一的前缀,例如 npm 包名称,以防止在侦听钩子时发生冲突。

triggerAsyncId#

triggerAsyncId 是导致(或“触发”)新资源初始化并导致调用 init 的资源的 asyncId。 这与 async_hooks.executionAsyncId() 不同,后者仅显示资源何时创建,而 triggerAsyncId 显示资源为何创建。

以下是 triggerAsyncId 的一个简单演示

import { createHook, executionAsyncId } from 'node:async_hooks';
import { stdout } from 'node:process';
import net from 'node:net';
import fs from 'node:fs';

createHook({
  init(asyncId, type, triggerAsyncId) {
    const eid = executionAsyncId();
    fs.writeSync(
      stdout.fd,
      `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
  },
}).enable();

net.createServer((conn) => {}).listen(8080);const { createHook, executionAsyncId } = require('node:async_hooks');
const { stdout } = require('node:process');
const net = require('node:net');
const fs = require('node:fs');

createHook({
  init(asyncId, type, triggerAsyncId) {
    const eid = executionAsyncId();
    fs.writeSync(
      stdout.fd,
      `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
  },
}).enable();

net.createServer((conn) => {}).listen(8080);

使用 nc localhost 8080 访问服务器时的输出

TCPSERVERWRAP(5): trigger: 1 execution: 1
TCPWRAP(7): trigger: 5 execution: 0 

TCPSERVERWRAP 是接收连接的服务器。

TCPWRAP 是来自客户端的新连接。 建立新连接时,会立即构造 TCPWrap 实例。 这发生在任何 JavaScript 堆栈之外。(executionAsyncId()0 意味着它正在从 C++ 执行,上面没有 JavaScript 堆栈。)仅凭该信息,不可能在什么导致它们被创建方面将资源链接在一起,因此 triggerAsyncId 的任务是传播哪个资源负责新资源的存在。

resource#

resource 是一个对象,表示已初始化的实际异步资源。 访问该对象的 API 可以由资源的创建者指定。 Node.js 本身创建的资源是内部资源,可以随时更改。 因此,未指定这些资源的 API。

在某些情况下,出于性能原因,资源对象会被重用,因此将其用作 WeakMap 中的键或向其添加属性是不安全的。

异步上下文示例#

上下文跟踪用例由稳定的 API AsyncLocalStorage 覆盖。 此示例仅说明异步钩子的操作,但 AsyncLocalStorage 更适合此用例。

以下示例包含有关 beforeafter 调用之间对 init 的调用的其他信息,特别是 listen() 的回调的样子。 输出格式略微详细,以便更容易看到调用上下文。

import async_hooks from 'node:async_hooks';
import fs from 'node:fs';
import net from 'node:net';
import { stdout } from 'node:process';
const { fd } = stdout;

let indent = 0;
async_hooks.createHook({
  init(asyncId, type, triggerAsyncId) {
    const eid = async_hooks.executionAsyncId();
    const indentStr = ' '.repeat(indent);
    fs.writeSync(
      fd,
      `${indentStr}${type}(${asyncId}):` +
      ` trigger: ${triggerAsyncId} execution: ${eid}\n`);
  },
  before(asyncId) {
    const indentStr = ' '.repeat(indent);
    fs.writeSync(fd, `${indentStr}before:  ${asyncId}\n`);
    indent += 2;
  },
  after(asyncId) {
    indent -= 2;
    const indentStr = ' '.repeat(indent);
    fs.writeSync(fd, `${indentStr}after:  ${asyncId}\n`);
  },
  destroy(asyncId) {
    const indentStr = ' '.repeat(indent);
    fs.writeSync(fd, `${indentStr}destroy:  ${asyncId}\n`);
  },
}).enable();

net.createServer(() => {}).listen(8080, () => {
  // Let's wait 10ms before logging the server started.
  setTimeout(() => {
    console.log('>>>', async_hooks.executionAsyncId());
  }, 10);
});const async_hooks = require('node:async_hooks');
const fs = require('node:fs');
const net = require('node:net');
const { fd } = process.stdout;

let indent = 0;
async_hooks.createHook({
  init(asyncId, type, triggerAsyncId) {
    const eid = async_hooks.executionAsyncId();
    const indentStr = ' '.repeat(indent);
    fs.writeSync(
      fd,
      `${indentStr}${type}(${asyncId}):` +
      ` trigger: ${triggerAsyncId} execution: ${eid}\n`);
  },
  before(asyncId) {
    const indentStr = ' '.repeat(indent);
    fs.writeSync(fd, `${indentStr}before:  ${asyncId}\n`);
    indent += 2;
  },
  after(asyncId) {
    indent -= 2;
    const indentStr = ' '.repeat(indent);
    fs.writeSync(fd, `${indentStr}after:  ${asyncId}\n`);
  },
  destroy(asyncId) {
    const indentStr = ' '.repeat(indent);
    fs.writeSync(fd, `${indentStr}destroy:  ${asyncId}\n`);
  },
}).enable();

net.createServer(() => {}).listen(8080, () => {
  // Let's wait 10ms before logging the server started.
  setTimeout(() => {
    console.log('>>>', async_hooks.executionAsyncId());
  }, 10);
});

仅启动服务器的输出

TCPSERVERWRAP(5): trigger: 1 execution: 1
TickObject(6): trigger: 5 execution: 1
before:  6
  Timeout(7): trigger: 6 execution: 6
after:   6
destroy: 6
before:  7
>>> 7
  TickObject(8): trigger: 7 execution: 7
after:   7
before:  8
after:   8 

如示例所示,executionAsyncId()execution 各自指定当前执行上下文的值;该上下文由对 beforeafter 的调用划定。

仅使用 execution 来绘制资源分配图会导致以下结果

  root(1)
     ^
     |
TickObject(6)
     ^
     |
 Timeout(7) 

TCPSERVERWRAP 不属于此图,即使它是调用 console.log() 的原因。 这是因为绑定到没有主机名的端口是一个同步操作,但为了维护完全异步的 API,用户的回调被放置在 process.nextTick() 中。 这就是为什么 TickObject 出现在输出中并且是 .listen() 回调的“父级”的原因。

该图仅显示资源何时创建,而不显示为何创建,因此要跟踪为何,请使用 triggerAsyncId。 这可以用以下图表示

 bootstrap(1)
     |
     ˅
TCPSERVERWRAP(5)
     |
     ˅
 TickObject(6)
     |
     ˅
  Timeout(7) 
before(asyncId)#

当异步操作启动(例如 TCP 服务器接收到新连接)或完成(例如将数据写入磁盘)时,会调用回调以通知用户。 before 回调在执行上述回调之前被调用。 asyncId 是分配给即将执行回调的资源的唯一标识符。

before 回调将被调用 0 到 N 次。 如果异步操作被取消,或者例如 TCP 服务器未收到任何连接,则 before 回调通常会被调用 0 次。 持久异步资源(如 TCP 服务器)通常会多次调用 before 回调,而其他操作(如 fs.open())只会调用一次。

after(asyncId)#

before 中指定的回调完成后立即调用。

如果在回调执行期间发生未捕获的异常,则 after 将在发出 'uncaughtException' 事件或运行 domain 的处理程序之后运行。

destroy(asyncId)#

在销毁与 asyncId 对应的资源后调用。 它也是从嵌入器 API emitDestroy() 异步调用的。

某些资源依赖于垃圾回收进行清理,因此如果引用传递给 initresource 对象,则 destroy 可能永远不会被调用,从而导致应用程序中的内存泄漏。 如果资源不依赖于垃圾回收,则这不是问题。

使用 destroy 钩子会导致额外的开销,因为它可以通过垃圾收集器跟踪 Promise 实例。

promiseResolve(asyncId)#

当调用传递给 Promise 构造函数的 resolve 函数时调用(直接或通过解析 promise 的其他方式)。

resolve() 不执行任何可观察到的同步工作。

如果 Promise 通过假定另一个 Promise 的状态来解析,则 Promise 不一定在此点被实现或拒绝。

new Promise((resolve) => resolve(true)).then((a) => {}); 

调用以下回调

init for PROMISE with id 5, trigger id: 1
  promise resolve 5      # corresponds to resolve(true)
init for PROMISE with id 6, trigger id: 5  # the Promise returned by then()
  before 6               # the then() callback is entered
  promise resolve 6      # the then() callback resolves the promise by returning
  after 6 

async_hooks.executionAsyncResource()#

  • 返回: <Object> 表示当前执行的资源。 用于在资源中存储数据非常有用。

executionAsyncResource() 返回的资源对象通常是具有未记录 API 的内部 Node.js 句柄对象。 在对象上使用任何函数或属性可能会使您的应用程序崩溃,应避免这样做。

在顶级执行上下文中使用 executionAsyncResource() 将返回一个空对象,因为没有要使用的句柄或请求对象,但拥有一个表示顶级的对象可能会有所帮助。

import { open } from 'node:fs';
import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';

console.log(executionAsyncId(), executionAsyncResource());  // 1 {}
open(new URL(import.meta.url), 'r', (err, fd) => {
  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap
});const { open } = require('node:fs');
const { executionAsyncId, executionAsyncResource } = require('node:async_hooks');

console.log(executionAsyncId(), executionAsyncResource());  // 1 {}
open(__filename, 'r', (err, fd) => {
  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap
});

这可以用于实现延续本地存储,而无需使用跟踪 Map 来存储元数据

import { createServer } from 'node:http';
import {
  executionAsyncId,
  executionAsyncResource,
  createHook,
} from 'node:async_hooks';
const sym = Symbol('state'); // Private symbol to avoid pollution

createHook({
  init(asyncId, type, triggerAsyncId, resource) {
    const cr = executionAsyncResource();
    if (cr) {
      resource[sym] = cr[sym];
    }
  },
}).enable();

const server = createServer((req, res) => {
  executionAsyncResource()[sym] = { state: req.url };
  setTimeout(function() {
    res.end(JSON.stringify(executionAsyncResource()[sym]));
  }, 100);
}).listen(3000);const { createServer } = require('node:http');
const {
  executionAsyncId,
  executionAsyncResource,
  createHook,
} = require('node:async_hooks');
const sym = Symbol('state'); // Private symbol to avoid pollution

createHook({
  init(asyncId, type, triggerAsyncId, resource) {
    const cr = executionAsyncResource();
    if (cr) {
      resource[sym] = cr[sym];
    }
  },
}).enable();

const server = createServer((req, res) => {
  executionAsyncResource()[sym] = { state: req.url };
  setTimeout(function() {
    res.end(JSON.stringify(executionAsyncResource()[sym]));
  }, 100);
}).listen(3000);

async_hooks.executionAsyncId()#

  • 返回: <number> 当前执行上下文的 asyncId。 用于跟踪何时调用某些内容非常有用。
import { executionAsyncId } from 'node:async_hooks';
import fs from 'node:fs';

console.log(executionAsyncId());  // 1 - bootstrap
const path = '.';
fs.open(path, 'r', (err, fd) => {
  console.log(executionAsyncId());  // 6 - open()
});const async_hooks = require('node:async_hooks');
const fs = require('node:fs');

console.log(async_hooks.executionAsyncId());  // 1 - bootstrap
const path = '.';
fs.open(path, 'r', (err, fd) => {
  console.log(async_hooks.executionAsyncId());  // 6 - open()
});

executionAsyncId() 返回的 ID 与执行时序有关,而不是因果关系(由 triggerAsyncId() 涵盖)

const server = net.createServer((conn) => {
  // Returns the ID of the server, not of the new connection, because the
  // callback runs in the execution scope of the server's MakeCallback().
  async_hooks.executionAsyncId();

}).listen(port, () => {
  // Returns the ID of a TickObject (process.nextTick()) because all
  // callbacks passed to .listen() are wrapped in a nextTick().
  async_hooks.executionAsyncId();
}); 

默认情况下,Promise 上下文可能无法获得精确的 executionAsyncIds。 请参阅有关promise 执行跟踪的部分。

async_hooks.triggerAsyncId()#

  • 返回: <number> 负责调用当前正在执行的回调的资源的 ID。
const server = net.createServer((conn) => {
  // The resource that caused (or triggered) this callback to be called
  // was that of the new connection. Thus the return value of triggerAsyncId()
  // is the asyncId of "conn".
  async_hooks.triggerAsyncId();

}).listen(port, () => {
  // Even though all callbacks passed to .listen() are wrapped in a nextTick()
  // the callback itself exists because the call to the server's .listen()
  // was made. So the return value would be the ID of the server.
  async_hooks.triggerAsyncId();
}); 

默认情况下,Promise 上下文可能无法获得有效的 triggerAsyncId。 请参阅有关promise 执行跟踪的部分。

async_hooks.asyncWrapProviders#

  • 返回:一个 provider 类型到相应数字 ID 的映射。 此映射包含 async_hooks.init() 事件可能发出的所有事件类型。

此功能抑制了不推荐使用的 process.binding('async_wrap').Providers 的使用。 请参阅:DEP0111

Promise 执行跟踪#

默认情况下,由于 V8 提供的 promise 内省 API 的相对昂贵的性质,promise 执行未分配 asyncId。 这意味着使用 promise 或 async/await 的程序默认情况下不会获得 promise 回调上下文的正确执行和触发器 ID。

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

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

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

请注意,即使存在异步跳转,then() 回调函数仍然声称是在外部作用域的上下文中执行的。此外,triggerAsyncId 的值为 0,这意味着我们缺少有关导致(触发)then() 回调函数执行的资源的上下文信息。

通过 async_hooks.createHook 安装异步钩子可以启用 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()}`);
});
// produces:
// 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()}`);
});
// produces:
// eid 7 tid 6

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

Promise 的另一个微妙之处在于,beforeafter 回调函数仅在链接的 Promise 上运行。这意味着不是由 then()/catch() 创建的 Promise 不会触发它们的 beforeafter 回调函数。有关更多详细信息,请参阅 V8 PromiseHooks API 的详细信息。

JavaScript 嵌入器 API#

处理自身异步资源(执行 I/O、连接池或管理回调队列等任务)的库开发者可以使用 AsyncResource JavaScript API,以便调用所有适当的回调函数。

类:AsyncResource#

该类的文档已移至 AsyncResource

类:AsyncLocalStorage#

该类的文档已移至 AsyncLocalStorage