triggerAsyncId
triggerAsyncId 是导致(或“触发”)新资源初始化并调用 init 的资源的 asyncId。这不同于 async_hooks.executionAsyncId(),后者只显示资源 何时 被创建,而 triggerAsyncId 显示的是资源被创建的 原因。
下面是一个关于 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.】