当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Node.js AsyncHook async_hooks.executionAsyncId()用法及代码示例

async_hooks.executionAsyncId()

历史
版本变化
v8.2.0

currentId 重命名。

v8.1.0

添加于:v8.1.0


参数
  • 返回: <number> 当前执行上下文的asyncId。有用的跟踪什么时候调用。
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()
});

executionAsyncId() 返回的 ID 与执行时间有关,而不是因果关系(由 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 execution tracking 部分。

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 async_hooks.executionAsyncId()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。