asyncLocalStorage.enterWith(store)
稳定性: 1 - 实验性
store<any>
在当前同步执行的其余部分中切换到上下文,然后在随后的任何异步调用中持久化存储。
【Transitions into the context for the remainder of the current synchronous execution and then persists the store through any following asynchronous calls.】
示例:
【Example:】
const store = { id: 1 };
// Replaces previous store with the given store object
asyncLocalStorage.enterWith(store);
asyncLocalStorage.getStore(); // Returns the store object
someAsyncOperation(() => {
asyncLocalStorage.getStore(); // Returns the same object
}); 这种过渡将持续整个同步执行过程。这意味着,例如,如果上下文在事件处理程序中被进入,后续的事件处理程序也将在该上下文中运行,除非使用 AsyncResource 明确绑定到另一个上下文。这就是为什么除非有强烈理由使用后者方法,否则应优先使用 run() 而不是 enterWith()。
【This transition will continue for the entire synchronous execution.
This means that if, for example, the context is entered within an event
handler subsequent event handlers will also run within that context unless
specifically bound to another context with an AsyncResource. That is why
run() should be preferred over enterWith() unless there are strong reasons
to use the latter method.】
const store = { id: 1 };
emitter.on('my-event', () => {
asyncLocalStorage.enterWith(store);
});
emitter.on('my-event', () => {
asyncLocalStorage.getStore(); // Returns the same object
});
asyncLocalStorage.getStore(); // Returns undefined
emitter.emit('my-event');
asyncLocalStorage.getStore(); // Returns the same object