如何保存回调以供以后使用node-addon-api?

时间:2019-01-21 17:40:34

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

我希望C库能够多次调用JS函数。我可以使用Nan来运行它,但是在将其转换为N-API / node-addon-api时遇到了麻烦。

如何保存JS回调函数并稍后从C调用它?

这是我在用Nan的东西:

Persistent<Function> r_log;
void sendLogMessageToJS(char* msg) {
    if (!r_log.IsEmpty()) {
        Isolate* isolate = Isolate::GetCurrent();
        Local<Function> func = Local<Function>::New(isolate, r_log);
        if (!func.IsEmpty()) {
        const unsigned argc = 1;
        Local<Value> argv[argc] = {
            String::NewFromUtf8(isolate, msg)
        };
        func->Call(Null(isolate), argc, argv);
        }
    }
}
NAN_METHOD(register_logger) {
    Isolate* isolate = info.GetIsolate();
    if (info[0]->IsFunction()) {
        Local<Function> func = Local<Function>::Cast(info[0]);
        Function * ptr = *func;
        r_log.Reset(isolate, func);
        myclibrary_register_logger(sendLogMessageToJS);
    } else {
        r_log.Reset();
    }
}

我该如何使用node-addon-api进行等效操作?我看到的所有示例都立即调用了回调或使用AsyncWorker以某种方式保存了回调。我不知道AsyncWorker的工作方式。

1 个答案:

答案 0 :(得分:0)

我从the node-addon-api maintainers得到了一个答案,这使我想到了这个解决方案:

FunctionReference r_log;
void emitLogInJS(char* msg) {
  if (r_log != nullptr) {
    Env env = r_log.Env();
    String message = String::New(env, msg);
    std::vector<napi_value> args = {message}; 
    r_log.Call(args);
  } 
}
void register_logger(const CallbackInfo& info) {
  r_log = Persistent(info[0].As<Function>());
  myclibrary_register_logger(emitLogInJS);
}
相关问题