napi_threadsafe_function_call_js
函数指针用于异步线程安全的函数调用。回调函数将在主线程上被调用。其目的是使用通过队列从某个辅助线程传来的数据项来构建调用 JavaScript 所需的参数,通常通过 napi_call_function,然后执行对 JavaScript 的调用。
【Function pointer used with asynchronous thread-safe function calls. The callback
will be called on the main thread. Its purpose is to use a data item arriving
via the queue from one of the secondary threads to construct the parameters
necessary for a call into JavaScript, usually via napi_call_function, and then
make the call into JavaScript.】
从次线程通过队列传来的数据在 data 参数中给出,要调用的 JavaScript 函数在 js_callback 参数中给出。
【The data arriving from the secondary thread via the queue is given in the data
parameter and the JavaScript function to call is given in the js_callback
parameter.】
Node-API 会在调用此回调之前设置好环境,因此通过 napi_call_function 调用 JavaScript 函数就足够了,而无需通过 napi_make_callback。
【Node-API sets up the environment prior to calling this callback, so it is
sufficient to call the JavaScript function via napi_call_function rather than
via napi_make_callback.】
回调函数必须满足以下签名:
【Callback functions must satisfy the following signature:】
typedef void (*napi_threadsafe_function_call_js)(napi_env env,
napi_value js_callback,
void* context,
void* data); [in] env:用于 API 调用的环境,如果线程安全函数正在被拆除且可能需要释放data,则为NULL。[in] js_callback:要调用的 JavaScript 函数,如果线程安全函数正在被销毁并且data可能需要释放,则为NULL。如果线程安全函数在创建时没有js_callback,它也可能为NULL。[in] context:创建线程安全函数时使用的可选数据。[in] data:由二级线程创建的数据。回调函数的责任是将这些本地数据转换为可以在调用js_callback时作为参数传递的 JavaScript 值(使用 Node-API 函数)。这个指针完全由线程和该回调函数管理。因此,该回调函数应释放这些数据。
除非出于 对象生命周期管理 中讨论的原因,否则在函数体内创建 handle 和/或回调作用域并非必要。
【Unless for reasons discussed in Object Lifetime Management, creating a handle and/or callback scope inside the function body is not necessary.】