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


Node.js AsyncHook async_hooks.executionAsyncResource()用法及代碼示例

async_hooks.executionAsyncResource()

添加於:v13.9.0、v12.17.0
  • 返回: <Object> 代表當前執行的資源。用於在資源中存儲數據。

executionAsyncResource() 返回的資源對象通常是帶有未記錄 API 的內部 Node.js 句柄對象。在對象上使用任何函數或屬性都可能使您的應用程序崩潰,應該避免。

在頂級執行上下文中使用executionAsyncResource() 將返回一個空對象,因為沒有要使用的句柄或請求對象,但是擁有一個表示頂級的對象可能會有所幫助。

import { open } from 'node:fs';
import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';

console.log(executionAsyncId(), executionAsyncResource());  // 1 {}
open(new URL(import.meta.url), 'r', (err, fd) => {
  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap
});const { open } = require('node:fs');
const { executionAsyncId, executionAsyncResource } = require('node:async_hooks');

console.log(executionAsyncId(), executionAsyncResource());  // 1 {}
open(__filename, 'r', (err, fd) => {
  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap
});

這可用於實現連續本地存儲,而無需使用跟蹤 Map 來存儲元數據:

import { createServer } from 'node:http';
import {
  executionAsyncId,
  executionAsyncResource,
  createHook
} from 'async_hooks';
const sym = Symbol('state'); // Private symbol to avoid pollution

createHook({
  init(asyncId, type, triggerAsyncId, resource) {
    const cr = executionAsyncResource();
    if (cr) {
      resource[sym] = cr[sym];
    }
  }
}).enable();

const server = createServer((req, res) => {
  executionAsyncResource()[sym] = { state: req.url };
  setTimeout(function() {
    res.end(JSON.stringify(executionAsyncResource()[sym]));
  }, 100);
}).listen(3000);const { createServer } = require('node:http');
const {
  executionAsyncId,
  executionAsyncResource,
  createHook
} = require('node:async_hooks');
const sym = Symbol('state'); // Private symbol to avoid pollution

createHook({
  init(asyncId, type, triggerAsyncId, resource) {
    const cr = executionAsyncResource();
    if (cr) {
      resource[sym] = cr[sym];
    }
  }
}).enable();

const server = createServer((req, res) => {
  executionAsyncResource()[sym] = { state: req.url };
  setTimeout(function() {
    res.end(JSON.stringify(executionAsyncResource()[sym]));
  }, 100);
}).listen(3000);

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 async_hooks.executionAsyncResource()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。