故障排除:上下文丢失


【Troubleshooting: Context loss】

在大多数情况下,AsyncLocalStorage 都能正常工作。在少数情况下,当前存储会在某个异步操作中丢失。

【In most cases, AsyncLocalStorage works without issues. In rare situations, the current store is lost in one of the asynchronous operations.】

如果你的代码是基于回调的,只需使用 util.promisify() 将其转换为 Promise,就可以开始使用原生 Promise。

【If your code is callback-based, it is enough to promisify it with util.promisify() so it starts working with native promises.】

如果你需要使用基于回调的 API,或者你的代码假设有自定义的 thenable 实现,请使用 AsyncResource 类将异步操作与正确的执行上下文关联起来。通过在你怀疑导致上下文丢失的调用之后记录 asyncLocalStorage.getStore() 的内容,找到导致上下文丢失的函数调用。当代码记录为 undefined 时,最后调用的回调很可能是导致上下文丢失的原因。

【If you need to use a callback-based API or your code assumes a custom thenable implementation, use the AsyncResource class to associate the asynchronous operation with the correct execution context. Find the function call responsible for the context loss by logging the content of asyncLocalStorage.getStore() after the calls you suspect are responsible for the loss. When the code logs undefined, the last callback called is probably responsible for the context loss.】