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_hooks init 钩子,并且可以通过 async_hooks.executionAsyncResource() 访问。
  • [in] async_resource_name:用于标识通过 async_hooks API 提供的诊断信息的资源类型。
  • [out] result:初始化的异步上下文。

如果 API 成功,则返回 napi_ok

【Returns napi_ok if the API succeeded.】

为了保持与以前版本的 ABI 兼容性,传递 NULLasync_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.】

该 API 的早期版本在 napi_async_context 对象存在期间并未保持对 async_resource 的强引用,而是期望调用者保持强引用。这一情况已被修改,因为无论如何,每次调用 napi_async_init() 都需要对应调用 napi_async_destroy,以避免内存泄漏。

【Previous versions of this API were not maintaining a strong reference to async_resource while the napi_async_context object existed and instead expected the caller to hold a strong reference. This has been changed, as a corresponding call to napi_async_destroy for every call to napi_async_init() is a requirement in any case to avoid memory leaks.】