channel.runStores(context, fn[, thisArg[, ...args]])
context<any> 发送给订阅者并绑定到商店的消息fn<Function> 处理程序将在输入的存储上下文中运行thisArg<any> 用于函数调用的接收对象。...args<any> 可选参数,传递给函数。
在给定函数的执行期间,将指定的数据应用到绑定到该通道的任何 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' })
});