asyncLocalStorage.withScope(store)


稳定性: 1 - 实验性

  • store <any>
  • 返回:RunScope

创建一个一次性作用域,该作用域进入指定的存储,并在作用域被释放时自动恢复先前的存储值。此方法设计用于与 JavaScript 的显式资源管理(using 语法)一起使用。

🌐 Creates a disposable scope that enters the given store and automatically restores the previous store value when the scope is disposed. This method is designed to work with JavaScript's explicit resource management (using syntax).

示例:

🌐 Example:

import { AsyncLocalStorage } from 'node:async_hooks';

const asyncLocalStorage = new AsyncLocalStorage();

{
  using _ = asyncLocalStorage.withScope('my-store');
  console.log(asyncLocalStorage.getStore()); // Prints: my-store
}

console.log(asyncLocalStorage.getStore()); // Prints: undefinedconst { AsyncLocalStorage } = require('node:async_hooks');

const asyncLocalStorage = new AsyncLocalStorage();

{
  using _ = asyncLocalStorage.withScope('my-store');
  console.log(asyncLocalStorage.getStore()); // Prints: my-store
}

console.log(asyncLocalStorage.getStore()); // Prints: undefined

withScope() 方法在管理同步代码中的上下文时特别有用,当你希望在退出一个代码块时,即使抛出错误,也能确保恢复之前的存储值。

🌐 The withScope() method is particularly useful for managing context in synchronous code where you want to ensure the previous store value is restored when exiting a block, even if an error is thrown.

import { AsyncLocalStorage } from 'node:async_hooks';

const asyncLocalStorage = new AsyncLocalStorage();

try {
  using _ = asyncLocalStorage.withScope('my-store');
  console.log(asyncLocalStorage.getStore()); // Prints: my-store
  throw new Error('test');
} catch (e) {
  // Store is automatically restored even after error
  console.log(asyncLocalStorage.getStore()); // Prints: undefined
}const { AsyncLocalStorage } = require('node:async_hooks');

const asyncLocalStorage = new AsyncLocalStorage();

try {
  using _ = asyncLocalStorage.withScope('my-store');
  console.log(asyncLocalStorage.getStore()); // Prints: my-store
  throw new Error('test');
} catch (e) {
  // Store is automatically restored even after error
  console.log(asyncLocalStorage.getStore()); // Prints: undefined
}

重要: 在异步函数中在第一次 await 之前使用 withScope() 时,请注意作用域的变化会影响调用者的上下文。异步函数的同步部分(在第一次 await 之前)在被调用时会立即执行,当它到达第一次 await 时,会将 Promise 返回给调用者。此时,作用域的变化在调用者的上下文中变得可见,并会在随后的同步代码中持续存在,直到其他操作改变作用域值。对于异步操作,建议使用 run(),它可以在异步边界正确隔离上下文。

import { AsyncLocalStorage } from 'node:async_hooks';

const asyncLocalStorage = new AsyncLocalStorage();

async function example() {
  using _ = asyncLocalStorage.withScope('my-store');
  console.log(asyncLocalStorage.getStore()); // Prints: my-store
  await someAsyncOperation(); // Function pauses here and returns promise
  console.log(asyncLocalStorage.getStore()); // Prints: my-store
}

// Calling without await
example(); // Synchronous portion runs, then pauses at first await
// After the promise is returned, the scope 'my-store' is now active in caller!
console.log(asyncLocalStorage.getStore()); // Prints: my-store (unexpected!)