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


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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。