我正在尝试使用 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 事件循环不会被阻塞并返回承诺?