我的主要问题是在插件中从 Node.js 调用异步函数并获取返回值。我正在尝试解决从被调用的 JS 函数返回的承诺。
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);
})
插件.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)
在 addon.cpp 我想调用异步 JS 函数并获取返回值