asyncLocalStorage.enterWith(store)


稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

转换为当前同步执行的剩余部分的上下文,然后通过任何后续异步调用持久保存存储。

¥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