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] env: The environment that the API is invoked under. -
[in] async_resource:与异步工作关联的对象,将传递给可能的async_hooksinit钩子 并可由async_hooks.executionAsyncResource()访问。¥
[in] async_resource: Object associated with the async work that will be passed to possibleasync_hooksinithooks and can be accessed byasync_hooks.executionAsyncResource(). -
[in] async_resource_name:为async_hooksAPI 公开的诊断信息提供的资源类型的标识符。¥
[in] async_resource_name: Identifier for the kind of resource that is being provided for diagnostic information exposed by theasync_hooksAPI. -
[out] result:初始化的异步上下文。¥
[out] result: The initialized async context.
如果 API 成功,则返回 napi_ok。
¥Returns napi_ok if the API succeeded.
async_resource 对象需要保持活动状态直到 napi_async_destroy 才能使 async_hooks 相关 API 正常运行。为了保持与之前版本的 ABI 兼容性,napi_async_context 没有维护对 async_resource 对象的强引用,以避免引入导致内存泄漏。但是,如果 async_resource 在 napi_async_context 被 napi_async_destroy 销毁之前被 JavaScript 引擎垃圾回收,那么在使用 AsyncLocalStorage API 时调用 napi_async_context 相关 API(如 napi_open_callback_scope 和 napi_make_callback)可能会导致异步上下文丢失等问题。
¥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 兼容性,为 async_resource 传递 NULL 不会导致错误。但是,不建议这样做,因为这会导致 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.