简体   繁体   English

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

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

I'm trying to call a nodejs async function from c++ that returns a promise that will be fufilled later using napi我正在尝试从 c++ 调用 nodejs 异步函数,该函数返回一个承诺,稍后将使用 napi 实现

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

I want to wait until the promise is finished and get napiStatus to be filled out with the resolved value rather than the handle to the promise.我想等到诺言完成,然后用已解决的值而不是诺言的句柄来填写 napiStatus。 Is there any way to do this?有没有办法做到这一点? I've gotten this to work when the function is not async and simply returns a value but my current requirements won't let me do that.当函数不是异步的并且只是返回一个值但我目前的要求不允许我这样做时,我已经让它工作了。

Here's an example function in JS that I want to call这是我要调用的 JS 中的示例函数

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

I want napiStatus to be the resolved value of 1 (after napi conversions).我希望 napiStatus 是 1 的解析值(在 napi 转换之后)。

You have to do the same as if you were doing it from JavaScript: call the .then() method of the Promise and register a callback.你必须像在 JavaScript 中那样做:调用 Promise 的.then()方法并注册一个回调。

Here is the complete example:这是完整的示例:

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});

The Callback function will receive the data from the resolved Promise: 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