繁体   English   中英

如何从 napi 本机代码调用 nodejs 异步函数并等待异步承诺解决

[英]How to call a nodejs async function from napi native code and wait until the async promise is resolved

我正在尝试从 c++ 调用 nodejs 异步函数,该函数返回一个承诺,稍后将使用 napi 实现

Napi::Value napiStatus = this->nodejsFunction.Call(someArgs)

我想等到诺言完成,然后用已解决的值而不是诺言的句柄来填写 napiStatus。 有没有办法做到这一点? 当函数不是异步的并且只是返回一个值但我目前的要求不允许我这样做时,我已经让它工作了。

这是我要调用的 JS 中的示例函数

function timedTest() {
  let timerExpired = new Promise((resolve,reject)=>{
    setTimeout(()=>{
      resolve(1);
    },3000)
  })
  return timerExpired;
}

我希望 napiStatus 是 1 的解析值(在 napi 转换之后)。

你必须像在 JavaScript 中那样做:调用 Promise 的.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函数将从已解析的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM