scope.dispose()
显式结束作用域并恢复之前的存储值。此方法是幂等的:多次调用与一次调用的效果相同。
🌐 Explicitly ends the scope and restores the previous store value. This method is idempotent: calling it multiple times has the same effect as calling it once.
[Symbol.dispose]() 方法委托给 dispose()。
🌐 The [Symbol.dispose]() method defers to dispose().
如果在没有使用 using 关键字的情况下调用 withScope(),必须手动调用 dispose() 来恢复先前的存储值。忘记调用 dispose() 会导致存储值在当前执行上下文的剩余时间内持续存在:
🌐 If withScope() is called without the using keyword, dispose() must be
called manually to restore the previous store value. Forgetting to call
dispose() will cause the store value to persist for the remainder of the
current execution context:
import { AsyncLocalStorage } from 'node:async_hooks';
const storage = new AsyncLocalStorage();
// Without using, the scope must be disposed manually
const scope = storage.withScope('my-store');
// storage.getStore() === 'my-store' here
scope.dispose(); // Restore previous value
// storage.getStore() === undefined hereconst { AsyncLocalStorage } = require('node:async_hooks');
const storage = new AsyncLocalStorage();
// Without using, the scope must be disposed manually
const scope = storage.withScope('my-store');
// storage.getStore() === 'my-store' here
scope.dispose(); // Restore previous value
// storage.getStore() === undefined here