[英]How to resolve Node.js Promise in N-Api Addon C
我的主要問題是在插件中從 Node.js 調用異步 function 並獲取返回值。 我正在嘗試解決從被調用的 JS function 返回的 promise。
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 我想調用 async JS function 並獲取返回值
對以下堆棧溢出帖子的回答也解釋了這種情況。 在該答案中,延遲 promise 的解決/拒絕正在CompleteMyPromise1() function 中完成。
您必須執行與從 JavaScript 執行相同的操作:調用 Promise 的 .then .then()
方法並注冊回調。
這是完整的示例:
Napi::Value ret = asyncFunction.Call({});
if (!ret.IsPromise())
throw Napi::Error::New(env, "your function did not return a Promise");
Napi::Promise promise = ret.As<Napi::Promise>();
Napi::Value thenValue = promise.Get("then");
if (!thenValue.IsFunction())
throw Napi::Error::New(env, "Promise is not thenable");
Napi::Function then = thenValue.As<Napi::Function>();
Napi::Function callback = Napi::Function::New(env, Callback, "cpp_callback");
then.Call(promise, {callback});
Callback
function 將從解析的 Promise 接收數據:
Napi::Value Callback(const Napi::CallbackInfo &info) {
printf("Callback called\n");
printf("Data: %s\n", info[0].ToString().Utf8Value().c_str());
return info.Env().Null();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.