故障排除:上下文丢失
¥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.