triggerAsyncId
triggerAsyncId
是导致(或 "triggered")新资源初始化并导致 init
调用的资源的 asyncId
。这不同于 async_hooks.executionAsyncId()
只显示资源创建时间,而 triggerAsyncId
显示资源创建原因。
¥triggerAsyncId
is the asyncId
of the resource that caused (or "triggered")
the new resource to initialize and that caused init
to call. This is different
from async_hooks.executionAsyncId()
that only shows when a resource was
created, while triggerAsyncId
shows why a resource was created.
下面是 triggerAsyncId
的简单演示:
¥The following is a simple demonstration of 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
访问服务器时的输出:
¥Output when hitting the server with nc localhost 8080
:
TCPSERVERWRAP(5): trigger: 1 execution: 1
TCPWRAP(7): trigger: 5 execution: 0
TCPSERVERWRAP
是接收连接的服务器。
¥The TCPSERVERWRAP
is the server which receives the connections.
TCPWRAP
是来自客户端的新连接。当建立新连接时,则立即构造 TCPWrap
实例。这发生在任何 JavaScript 堆栈之外。(executionAsyncId()
或 0
意味着它是从 C++ 执行的,上面没有 JavaScript 堆栈。)仅凭该信息,不可能根据资源创建的原因将资源链接在一起,因此 triggerAsyncId
的任务是传播哪些资源负责新资源的存在。
¥The TCPWRAP
is the new connection from the client. When a new
connection is made, the TCPWrap
instance is immediately constructed. This
happens outside of any JavaScript stack. (An executionAsyncId()
of 0
means
that it is being executed from C++ with no JavaScript stack above it.) With only
that information, it would be impossible to link resources together in
terms of what caused them to be created, so triggerAsyncId
is given the task
of propagating what resource is responsible for the new resource's existence.