如何使用返回承诺的NAPI创建异步函数

编程入门 行业动态 更新时间:2024-10-09 22:23:12

<a href=https://www.elefans.com/category/jswz/34/1771452.html style=如何使用返回承诺的NAPI创建异步函数"/>

如何使用返回承诺的NAPI创建异步函数

我正在尝试使用NAPI创建节点模块。我必须创建一个返回诺言的异步函数。我不希望testasynfunction阻塞NodeJS事件循环。 do_something_asynchronous是一个同步函数。

napi_deferred do_something_synchronous(napi_env env,napi_deferred deferred){
  printf("\n3) Function called");
  //napi_deferred deferred;
  napi_value undefined;
  napi_status status;

  // Create a value with which to conclude the deferred.
  status = napi_get_undefined(env, &undefined);
  if (status != napi_ok) return NULL;
  sleep(5);
  // Resolve or reject the promise associated with the deferred depending on
  // whether the asynchronous action succeeded.
  if (false) {
    printf("\n5) Success\nXXXXXXX");
    status = napi_resolve_deferred(env, deferred, undefined);
  } else {
    printf("\nReject");
    status = napi_reject_deferred(env, deferred, undefined);
  }
  if (status != napi_ok) return NULL;

  // At this point the deferred has been freed, so we should assign NULL to it.
  deferred = NULL;
}

//Function will be called from the js 
napi_value testasynfunction(napi_env env, napi_callback_info info){
  printf("XXXXX Hello \n");
  napi_deferred deferred;
  napi_value promise;
  napi_status status;
  // Create the promise.
  status = napi_create_promise(env, &deferred, &promise);
  if (status != napi_ok) return NULL;
  printf("\n1) Calling function to do something");
  do_something_synchronous(env,deferred);
  //std::async(do_something_asynchronous,env,deferred);
  printf("\n2) Returning Promise");
  return promise;
}
napi_property_descriptor testasync = DECLARE_NAPI_METHOD("testasyn", testasynfunction);
  status = napi_define_properties(env, exports, 1, &testasync);
  assert(status == napi_ok);

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)

问题:1)我该如何异步运行do_something_synchronous,以便nodejs事件循环不会被阻塞并返回诺言?

回答如下:

以下代码段是此异步操作的关键组件。napi_create_async_work()函数分配一个工作对象,我们可以在其中指定工作者处理程序函数,例如在我们的案例中,[[ExecuteMyPromise1()(可以与它一起部署运行时间长或处理繁重的任务)。 此函数将作为工作池线程的队列它将与node.js主事件循环线程并行异步执行

到目前为止一切看起来都不错,当ExecuteMyPromise1函数计划直接从工作线程与JavaScript层交换结果时,就会出现问题。

任何JavaScript操作通常只能从本机插件的主线程中调用

。然后,为了进行结果交换,我们必须使用另一个将从主线程调用的本机函数。这就是为什么我们使用CompleteMyPromise1函数处理程序。当异步逻辑完成或被取消时,将从本地事件循环线程中调用此本地函数。 // The function called by javascript to get a promise returned. napi_value MyPromise1(napi_env env, napi_callback_info info) { // -- -- -- -- // -- -- -- -- // Create a promise object. status = napi_create_promise(env, &promDataEx->deferred, &promise); if (status != napi_ok) { napi_throw_error(env, NULL, "Unable to create promise."); } // -- -- -- -- // -- -- -- -- { // Create the async function. napi_value resource_name; napi_create_string_utf8(env, "MyPromise1", -1, &resource_name); napi_create_async_work(env, NULL, resource_name, ExecuteMyPromise1, CompleteMyPromise1, promDataEx, &promDataEx->work); napi_queue_async_work(env, promDataEx->work); } return promise; }
// Execute the asynchronous work.
void ExecuteMyPromise1(napi_env env, void *data)
{
    prom_data_ex_t *promDataEx = (prom_data_ex_t *)data;

    // Calculate prime count
    promDataEx->PrimeCount = CPrimeCount( promDataEx->x, promDataEx->y );

    // Set the status as asynchronous_action is success
    promDataEx->asynchronous_action_status = 0;
    //sleep(3);
}
// Handle the completion of the asynchronous work.
void CompleteMyPromise1(napi_env env, napi_status status, void *data)
{
    napi_value rcValue;

    prom_data_ex_t *promDataEx = (prom_data_ex_t *)data;

    napi_create_int32(env, promDataEx->PrimeCount, &rcValue);

    // Resolve or reject the promise associated with the deferred depending on
    // whether the asynchronous action succeeded.
    if ( promDataEx->asynchronous_action_status == 0) // Success
    {
        status = napi_resolve_deferred(env, promDataEx->deferred, rcValue);
    }
    else
    {
        napi_value undefined;

        status = napi_get_undefined(env, &undefined);
        status = napi_reject_deferred(env, promDataEx->deferred, undefined );
    }
    if (status != napi_ok)
    {
        napi_throw_error(env, NULL, "Unable to create promise result.");
    }

    napi_delete_async_work(env, promDataEx->work);
    free(promDataEx);
}
这里是完整的示例代码https://github/msatyan/MyNodeC/blob/master/src/mync1/MyPromise1.cpp

JavaScrip调用为TestPromiseWithAsync()https://github/msatyan/MyNodeC/blob/master/test/TestExtensions.js

更多推荐

如何使用返回承诺的NAPI创建异步函数

本文发布于:2024-05-13 11:05:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759462.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   函数   NAPI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!