async_hooks.executionAsyncId()
- 返回: <number> 当前执行上下文的
asyncId
。 当有调用时对跟踪很有用。
import { executionAsyncId } from 'node:async_hooks';
console.log(executionAsyncId()); // 1 - 引导
fs.open(path, 'r', (err, fd) => {
console.log(executionAsyncId()); // 6 - open()
});
const async_hooks = require('node:async_hooks');
console.log(async_hooks.executionAsyncId()); // 1 - 引导
fs.open(path, 'r', (err, fd) => {
console.log(async_hooks.executionAsyncId()); // 6 - open()
});
executionAsyncId()
返回的 ID 与执行时机有关,与因果无关(被 triggerAsyncId()
涵盖):
const server = net.createServer((conn) => {
// 返回服务器的 ID,而不是新连接的 ID,
// 因为回调在服务器的 MakeCallback() 的执行范围内运行。
async_hooks.executionAsyncId();
}).listen(port, () => {
// 返回 TickObject (process.nextTick()) 的 ID,
// 因为传给 .listen() 的所有回调都包含在 nextTick() 中。
async_hooks.executionAsyncId();
});
默认情况下,promise 上下文可能无法获得精确的 executionAsyncIds
。
请参阅 promise 执行跟踪部分。
- Returns: <number> The
asyncId
of the current execution context. Useful to track when something calls.
import { executionAsyncId } from 'node:async_hooks';
console.log(executionAsyncId()); // 1 - bootstrap
fs.open(path, 'r', (err, fd) => {
console.log(executionAsyncId()); // 6 - open()
});
const async_hooks = require('node:async_hooks');
console.log(async_hooks.executionAsyncId()); // 1 - bootstrap
fs.open(path, 'r', (err, fd) => {
console.log(async_hooks.executionAsyncId()); // 6 - open()
});
The ID returned from executionAsyncId()
is related to execution timing, not
causality (which is covered by 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 contexts may not get precise executionAsyncIds
by default.
See the section on promise execution tracking.