These classes are used to associate state and propagate it throughout callbacks and promise chains. They allow storing data throughout the lifetime of a web request or any other asynchronous duration. It is similar to thread-local storage in other languages.
AsyncLocalStorage
官方文件提供的範例也是用於處理logger context的傳遞議題
The following example uses
AsyncLocalStorage
to build a simple logger that assigns IDs to incoming HTTP requests and includes them in messages logged within each request.
AsyncLocalStorage was first introduced in Node.js version 12.0.0, released on April 23, 2019.
AsyncLocalStorage 直接基於 async_hooks 進行封裝。而 async_hooks 對於性能有一定的影響,在高並發的場景,大家對此 API 保持了謹慎的態度。
但隨後 v8 engine 出現了 v8::Context PromiseHook API,開發人員將其引入後的新版本極大提升了性能
Performed 45 iterations to warmup
Performed 4202 iterations (with ALS enabled)
Performed 4277 iterations (with ALS disabled)
ALS penalty: 1.75%
reddit 兩邊感想:
其他參考資料:
enterWith()
。