channel.withStoreScope(data)


稳定性: 1 - 实验性

  • data <any> 绑定到存储的消息
  • 返回:RunStoresScope 一次性作用域对象

创建一个一次性作用域,将给定数据绑定到绑定到通道的任何 AsyncLocalStorage 实例,并将其发布给订阅者。该作用域在释放时会自动恢复之前的存储上下文。

🌐 Creates a disposable scope that binds the given data to any AsyncLocalStorage instances bound to the channel and publishes it to subscribers. The scope automatically restores the previous storage contexts when disposed.

这种方法可以使用 JavaScript 的显式资源管理(使用 using 语法和 Symbol.dispose)来管理存储上下文,而无需闭包封装。

🌐 This method enables the use of JavaScript's explicit resource management (using syntax with Symbol.dispose) to manage store contexts without closure wrapping.

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

const store = new AsyncLocalStorage();
const ch = channel('my-channel');

ch.bindStore(store, (message) => {
  return { ...message, timestamp: Date.now() };
});

{
  using scope = ch.withStoreScope({ request: 'data' });
  // Store is entered, data is published
  console.log(store.getStore()); // { request: 'data', timestamp: ... }
}
// Store is automatically restored on scope exitconst { channel } = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');

const store = new AsyncLocalStorage();
const ch = channel('my-channel');

ch.bindStore(store, (message) => {
  return { ...message, timestamp: Date.now() };
});

{
  using scope = ch.withStoreScope({ request: 'data' });
  // Store is entered, data is published
  console.log(store.getStore()); // { request: 'data', timestamp: ... }
}
// Store is automatically restored on scope exit