napi_async_init
napi_status napi_async_init(napi_env env,
napi_value async_resource,
napi_value async_resource_name,
napi_async_context* result) [in] env:调用该 API 时所处的环境。[in] async_resource:与异步工作相关的对象,它将传递给可能的async_hooksinit钩子,并且可以通过async_hooks.executionAsyncResource()访问。[in] async_resource_name:用于标识通过async_hooksAPI 提供的诊断信息的资源类型。[out] result:初始化的异步上下文。
如果 API 成功,则返回 napi_ok。
【Returns napi_ok if the API succeeded.】
async_resource 对象需要保持存活直到 napi_async_destroy,以确保 async_hooks 相关的 API 正常工作。为了与之前版本保持 ABI 兼容,napi_async_context 并不会对 async_resource 对象保持强引用,以避免引入可能的内存泄漏。然而,如果在 napi_async_context 被 napi_async_destroy 销毁之前,async_resource 被 JavaScript 引擎回收,调用 napi_async_context 相关的 API(例如 napi_open_callback_scope 和 napi_make_callback)可能会导致使用 AsyncLocalStorage API 时异步上下文丢失等问题。
【The async_resource object needs to be kept alive until
napi_async_destroy to keep async_hooks related API acts correctly. In
order to retain ABI compatibility with previous versions, napi_async_contexts
are not maintaining the strong reference to the async_resource objects to
avoid introducing causing memory leaks. However, if the async_resource is
garbage collected by JavaScript engine before the napi_async_context was
destroyed by napi_async_destroy, calling napi_async_context related APIs
like napi_open_callback_scope and napi_make_callback can cause
problems like loss of async context when using the AsyncLocalStorage API.】
为了保持与以前版本的 ABI 兼容性,传递 NULL 给 async_resource 并不会导致错误。然而,这不推荐使用,因为这会导致与 async_hooks init 钩子 和 async_hooks.executionAsyncResource() 的行为不符合预期,因为底层的 async_hooks 实现现在需要该资源以提供异步回调之间的关联。
【In order to retain ABI compatibility with previous versions, passing NULL
for async_resource does not result in an error. However, this is not
recommended as this will result in undesirable behavior with async_hooks
init hooks and async_hooks.executionAsyncResource() as the resource is
now required by the underlying async_hooks implementation in order to provide
the linkage between async callbacks.】