【问题标题】:How to resolve Node.js Promise in N-Api Addon C如何在 N-Api Addon C 中解决 Node.js Promise
【发布时间】:2020-11-26 14:05:22
【问题描述】:

我的主要问题是在插件中从 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函数并获取返回值

我以这个文档为例 https://nodejs.org/api/n-api.html#n_api_promises

【问题讨论】:

    标签: c++ node.js c node.js-addon n-api


    【解决方案1】:

    以下堆栈溢出帖子的答案也解释了这种情况。在那个答案中,延迟承诺的 resolve/reject 正在 CompleteMyPromise1() 函数中完成。

    How to create async function using NAPI that return Promises

    【讨论】:

    • 你调用 do_something_asynchronous() 的方式并不是真正的异步调用,它是阻塞调用,就像任何其他 C 函数调用一样。
    • 谢谢,有关事件循环阻塞的信息将对我有所帮助。但我需要一些不同的东西。在您的示例中,您将 Promise 从 Addon 返回到 Node.js 和 Node.js 应用程序解决它。我需要相反的 - Node.js 将 Promise 传递给 Addon 并 Addon 解决它。你知道怎么做吗?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 2022-01-25
    • 1970-01-01
    • 2020-10-06
    相关资源
    最近更新 更多