Node.js v25.0.0 文档
- Node.js v25.0.0
- 目录
-
索引
- 断言测试
- 异步上下文跟踪
- 异步钩子
- 缓冲区
- C++ 插件
- 使用 Node-API 的 C/C++ 插件
- C++ 嵌入器 API
- 子进程
- 集群
- 命令行选项
- 控制台
- 加密
- 调试器
- 已弃用的 API
- 诊断通道
- DNS
- 域
- 环境变量
- 错误
- 事件
- 文件系统
- 全局对象
- HTTP
- HTTP/2
- HTTPS
- 检查器
- 国际化
- 模块:CommonJS 模块
- 模块:ECMAScript 模块
- 模块:
node:module
API - 模块:包
- 模块:TypeScript
- 网络
- 操作系统
- 路径
- 性能钩子
- 权限
- 进程
- Punycode
- 查询字符串
- 逐行读取
- REPL
- 报告
- 单一可执行文件应用
- SQLite
- 流
- 字符串解码器
- 测试运行器
- 定时器
- TLS/SSL
- 跟踪事件
- TTY
- UDP/数据报
- URL
- 实用工具
- V8
- 虚拟机
- WASI
- Web Crypto API
- Web Streams API
- 工作线程
- Zlib
- 其他版本
- 选项
异步钩子#
createHook
、AsyncHook
和 executionAsyncResource
API,因为它们存在可用性问题、安全风险和性能影响。异步上下文跟踪的用例最好由稳定的 AsyncLocalStorage
API 来满足。如果您有超出 AsyncLocalStorage
解决的上下文跟踪需求或 诊断通道 当前提供的诊断数据之外的 createHook
、AsyncHook
或 executionAsyncResource
的用例,请在 https://github.com/nodejs/node/issues 上提交一个 issue,描述您的用例,以便我们创建一个更具针对性的 API。源代码: lib/async_hooks.js
我们强烈不鼓励使用 async_hooks
API。其他可以覆盖其大部分用例的 API 包括:
AsyncLocalStorage
跟踪异步上下文process.getActiveResourcesInfo()
跟踪活动资源
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)
#
callbacks
<Object> 要注册的 钩子回调函数init
<Function>init
回调。before
<Function>before
回调。after
<Function>after
回调。destroy
<Function>destroy
回调。promiseResolve
<Function>promiseResolve
回调。
- 返回: <AsyncHook> 用于禁用和启用钩子的实例
注册用于每个异步操作的不同生命周期事件的回调函数。
回调函数 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 是通过 async hooks 机制跟踪其生命周期的异步资源,所以 init()
、before()
、after()
和 destroy()
回调*不能*是返回 Promise 的异步函数。
错误处理#
如果任何 AsyncHook
回调抛出异常,应用程序将打印堆栈跟踪并退出。退出路径遵循未捕获异常的路径,但所有 'uncaughtException'
监听器都会被移除,从而强制进程退出。'exit'
回调仍然会被调用,除非应用程序使用 --abort-on-uncaught-exception
运行,在这种情况下,将打印堆栈跟踪并退出应用程序,留下一个核心文件。
这种错误处理行为的原因是,这些回调在对象生命周期中可能不稳定的点上运行,例如在类构造和析构期间。因此,为了防止将来发生意外中止,有必要迅速关闭进程。如果进行了全面的分析以确保异常可以遵循正常的控制流而没有意外的副作用,这一点将来可能会改变。
在 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
实例启用回调。如果没有提供回调,启用是一个空操作。
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
的引用。
从全局的 AsyncHook
回调池中禁用给定 AsyncHook
实例的回调。一旦钩子被禁用,它将不会再次被调用,直到被启用。
为了 API 的一致性,disable()
也会返回 AsyncHook
实例。
钩子回调#
异步事件生命周期中的关键事件被分为四个领域:实例化、回调调用前后,以及实例销毁时。
init(asyncId, type, triggerAsyncId, resource)
#
asyncId
<number> 异步资源的唯一 ID。type
<string> 异步资源的类型。triggerAsyncId
<number> 创建此异步资源的异步资源的执行上下文的唯一 ID。resource
<Object> 对代表异步操作的资源的引用,需要在 destroy 期间释放。
当一个类被构造时,如果它有*可能*触发一个异步事件,就会调用此函数。这*并不*意味着该实例必须在调用 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));
每个新资源都会被分配一个在当前 Node.js 实例范围内唯一的 ID。
type
#
type
是一个字符串,用于标识导致 init
被调用的资源类型。通常,它对应于资源构造函数的名称。
Node.js 本身创建的资源的 type
在任何 Node.js 版本中都可能改变。有效值包括 TLSWRAP
、TCPWRAP
、TCPSERVERWRAP
、GETADDRINFOREQWRAP
、FSREQCALLBACK
、Microtask
和 Timeout
。请检查所使用的 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
更适合此用例。
以下是一个示例,其中包含有关在 before
和 after
调用之间对 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
各自指定了当前执行上下文的值;该上下文由对 before
和 after
的调用来划分。
仅使用 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)
#
asyncId
<number>
当一个异步操作启动(例如 TCP 服务器接收到一个新连接)或完成(例如将数据写入磁盘)时,会调用一个回调来通知用户。before
回调就在该回调执行之前被调用。asyncId
是分配给即将执行回调的资源的唯一标识符。
before
回调将被调用 0 到 N 次。如果异步操作被取消,或者例如 TCP 服务器没有收到任何连接,before
回调通常会被调用 0 次。像 TCP 服务器这样的持久性异步资源通常会多次调用 before
回调,而像 fs.open()
这样的其他操作只会调用一次。
after(asyncId)
#
asyncId
<number>
在 before
中指定的回调完成后立即调用。
如果在回调执行期间发生未捕获的异常,那么 after
将在 'uncaughtException'
事件被触发或 domain
的处理程序运行*之后*运行。
destroy(asyncId)
#
asyncId
<number>
在与 asyncId
对应的资源被销毁后调用。它也由嵌入器 API emitDestroy()
异步调用。
一些资源的清理依赖于垃圾回收,所以如果对传递给 init
的 resource
对象进行了引用,那么 destroy
可能永远不会被调用,导致应用程序中出现内存泄漏。如果资源不依赖于垃圾回收,那么这就不是问题。
使用 destroy 钩子会产生额外的开销,因为它通过垃圾收集器启用了对 Promise
实例的跟踪。
promiseResolve(asyncId)
#
asyncId
<number>
当传递给 Promise
构造函数的 resolve
函数被调用时(无论是直接调用还是通过其他方式解析一个 promise),此回调会被调用。
resolve()
不会执行任何可观察的同步工作。
如果一个 Promise
是通过采纳另一个 Promise
的状态来解析的,那么此时这个 Promise
不一定已经 fulfilled 或 rejected。
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()
返回的资源对象通常是内部的 Node.js 句柄对象,其 API 未被文档化。使用该对象上的任何函数或属性都可能导致您的应用程序崩溃,应避免使用。
在顶级执行上下文中使用 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
});
这可以用于实现连续局部存储(continuation local storage),而无需使用跟踪 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 执行跟踪的部分。
Promise 执行跟踪#
默认情况下,promise 的执行不会被分配 asyncId
,因为 V8 提供的 promise 自省 API 相对昂贵。这意味着使用 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 0
const { 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 6
const { 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 的 asyncId
是 6
,后者的 asyncId
是 7
。在执行 then()
回调期间,我们是在 asyncId
为 7
的 promise 的上下文中执行。这个 promise 是由异步资源 6
触发的。
promise 的另一个微妙之处在于,before
和 after
回调只在链式 promise 上运行。这意味着非由 then()
/catch()
创建的 promise 不会触发 before
和 after
回调。更多细节请参见 V8 的 PromiseHooks API 的详细信息。
JavaScript 嵌入器 API#
处理自己的异步资源(如 I/O、连接池或管理回调队列)的库开发人员可以使用 AsyncResource
JavaScript API,以便调用所有适当的回调。
类: AsyncResource
#
该类的文档已移至 AsyncResource
。
类: AsyncLocalStorage
#
该类的文档已移至 AsyncLocalStorage
。