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() 覆盖):

【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 上下文可能无法获得精确的 executionAsyncIds。请参阅 承诺执行跟踪 部分。

【Promise contexts may not get precise executionAsyncIds by default. See the section on promise execution tracking.】