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) => {
  // 返回服务器的 ID,而不是新连接的 ID,因为
  // 回调在服务器的 MakeCallback() 执行作用域中运行。
  async_hooks.executionAsyncId();

}).listen(port, () => {
  // 返回 TickObject (process.nextTick()) 的 ID,因为所有
  // 传给 .listen() 的回调都包装在 nextTick() 中。
  async_hooks.executionAsyncId();
}); 

默认情况下,Promise 上下文可能不会获得精确的 executionAsyncIds。 请参阅 promise 执行跟踪 一节。