napi_make_callback


NAPI_EXTERN napi_status napi_make_callback(napi_env env,
                                           napi_async_context async_context,
                                           napi_value recv,
                                           napi_value func,
                                           size_t argc,
                                           const napi_value* argv,
                                           napi_value* result); 
  • [in] env:调用该 API 时所处的环境。
  • [in] async_context:用于调用回调的异步操作的上下文。通常,这应是先前从 napi_async_init 获取的值。为了保持与之前版本的 ABI 兼容性,将 async_context 传递为 NULL 不会导致错误。然而,这会导致异步钩子的操作不正确。潜在问题包括在使用 AsyncLocalStorage API 时异步上下文丢失。
  • [in] recv:传递给被调用函数的 this 值。
  • [in] func:表示要调用的 JavaScript 函数的 napi_value
  • [in] argcargv 数组中元素的数量。
  • [in] argv:作为 napi_value 的 JavaScript 值数组,表示传递给函数的参数。如果 argc 为零,则可以通过传入 NULL 来省略此参数。
  • [out] resultnapi_value,表示返回的 JavaScript 对象。

如果 API 成功,则返回 napi_ok

【Returns napi_ok if the API succeeded.】

此方法允许从本地插件调用 JavaScript 函数对象。该 API 类似于 napi_call_function。然而,它用于在从异步操作返回后(当调用栈上没有其他脚本时)从本地代码回调到 JavaScript。它是围绕 node::MakeCallback 的一个相当简单的封装。

【This method allows a JavaScript function object to be called from a native add-on. This API is similar to napi_call_function. However, it is used to call from native code back into JavaScript after returning from an async operation (when there is no other script on the stack). It is a fairly simple wrapper around node::MakeCallback.】

请注意,从 napi_async_complete_callback 内部需要使用 napi_make_callback;在这种情况下,回调的异步上下文已经设置完毕,因此直接调用 napi_call_function 就足够且适当。在实现不使用 napi_create_async_work 的自定义异步行为时,可能需要使用 napi_make_callback 函数。

【Note it is not necessary to use napi_make_callback from within a napi_async_complete_callback; in that situation the callback's async context has already been set up, so a direct call to napi_call_function is sufficient and appropriate. Use of the napi_make_callback function may be required when implementing custom async behavior that does not use napi_create_async_work.】

在回调期间,JavaScript 安排在微任务队列中的任何 process.nextTick 或 Promise 都会在返回到 C/C++ 之前执行。

【Any process.nextTicks or Promises scheduled on the microtask queue by JavaScript during the callback are ran before returning back to C/C++.】