當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。