My main problem is to call the asynchronous function from Node.js in addon and get the returned value. I am trying to resolve the promise returned from the called JS function.
index.js
const addon = require('./build/Debug/addon.node');
async function asunc_func() {
return "Hello asunc_func";
}
const result = addon.test_async(asunc_func); // addon returned a promise
result.then(res => {
console.log(res);
})
addon.cpp
#include <napi.h>
using namespace Napi;
int do_something_asynchronous(napi_deferred deferred, Napi::Function func, Napi::Env env) {
napi_value undefined;
napi_status status;
status = napi_get_undefined(env, &undefined);
if (status != napi_ok) return 0;
napi_value result = func.Call({});
// I want to get the string "Hello asunc_func" here
// from called JS function
napi_valuetype * result_type;
status = napi_typeof(env, result, result_type); // result_type: napi_object
if (result) {
status = napi_resolve_deferred(env, deferred, result);
} else {
status = napi_reject_deferred(env, deferred, undefined);
}
if (status != napi_ok) return 0;
deferred = NULL;
}
napi_value test_async(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::Function func = info[0].As<Napi::Function>();
napi_deferred deferred;
napi_value promise;
napi_status status;
status = napi_create_promise(env, &deferred, &promise);
if (status != napi_ok) return NULL;
do_something_asynchronous(deferred, func, env);
return promise;
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "test_async"), Napi::Function::New(env, test_async));
return exports;
}
NODE_API_MODULE(addon, Init)
In addon.cpp I want to call async JS function and get the returned value
I used this doc as example https://nodejs.org/api/n-api.html#n_api_promises
Answer to the following stack overflow post is explaining this scenario too. In that answer the resolve/reject of the deferred promise is being done in CompleteMyPromise1() function.
How to create async function using NAPI that return Promises
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With