channel.runStores(context, fn[, thisArg[, ...args]])


稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

  • context <any> 发送给订阅者并绑定到存储的消息

    ¥context <any> Message to send to subscribers and bind to stores

  • fn <Function> 在输入的存储上下文中运行的处理程序

    ¥fn <Function> Handler to run within the entered storage context

  • thisArg <any> 用于函数调用的接收器。

    ¥thisArg <any> The receiver to be used for the function call.

  • ...args <any> 传递给函数的可选参数。

    ¥...args <any> Optional arguments to pass to the function.

在给定函数的持续时间内将给定数据应用于绑定到通道的任何 AsyncLocalStorage 实例,然后在该数据应用于存储的范围内发布到通道。

¥Applies the given data to any AsyncLocalStorage instances bound to the channel for the duration of the given function, then publishes to the channel within the scope of that data is applied to the stores.

如果为 channel.bindStore(store) 提供了转换函数,它将在消息数据成为存储的上下文值之前应用于转换消息数据。在需要上下文链接的情况下,可以从转换函数中访问先前的存储上下文。

¥If a transform function was given to channel.bindStore(store) it will be applied to transform the message data before it becomes the context value for the store. The prior storage context is accessible from within the transform function in cases where context linking is required.

应用于存储的上下文应该可以在从给定函数期间开始的执行继续的任何异步代码中访问,但是在某些情况下可能会发生 上下文丢失

¥The context applied to the store should be accesible in any async code which continues from execution which began during the given function, however there are some situations in which context loss may occur.

import diagnostics_channel from 'node:diagnostics_channel';
import { AsyncLocalStorage } from 'node:async_hooks';

const store = new AsyncLocalStorage();

const channel = diagnostics_channel.channel('my-channel');

channel.bindStore(store, (message) => {
  const parent = store.getStore();
  return new Span(message, parent);
});
channel.runStores({ some: 'message' }, () => {
  store.getStore(); // Span({ some: 'message' })
});const diagnostics_channel = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');

const store = new AsyncLocalStorage();

const channel = diagnostics_channel.channel('my-channel');

channel.bindStore(store, (message) => {
  const parent = store.getStore();
  return new Span(message, parent);
});
channel.runStores({ some: 'message' }, () => {
  store.getStore(); // Span({ some: 'message' })
});