我将 a 传递Napi::Promise::Deferred
给 AsyncWorker,然后调用Promise::Defered.Resolve()
AynscWork.OnOK。但是当我调用 Resolve() 时它总是崩溃
// node addon function
Napi::Promise FileMd5Async(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
auto filePath = info[0].As<Napi::String>().Utf8Value();
Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
HashAsyncWorker *hashAsyncWorker = new HashAsyncWorker(env, deferred, filePath);
hashAsyncWorker->Queue();
return deferred.Promise();
}
// HashAsyncWorker.h
#pragma once
#include "third_party/node-addon-api/napi.h"
class HashAsyncWorker : public Napi::AsyncWorker {
public:
HashAsyncWorker(Napi::Env &env, Napi::Promise::Deferred& deferred, std::string filePath);
~HashAsyncWorker() override {};
void Execute() override;
void OnOK() override;
void OnError(Napi::Error const &error) override;
private:
Napi::Env &env;
Napi::Promise::Deferred& deferred;
std::string filePath;
std::string hashResult;
};
// // HashAsyncWorker.cc
#include "HashAsyncWorker.H"
#include "hash_utils.h"
HashAsyncWorker::HashAsyncWorker(Napi::Env &env, Napi::Promise::Deferred& deferred, std::string filePath) : Napi::AsyncWorker(env), env(env), deferred(deferred), filePath(filePath), hashResult("") {
}
void HashAsyncWorker::Execute() {
hashResult = hash_utils::FileMd5(filePath);
}
void HashAsyncWorker::OnOK() {
// crash here
//[1] 37056 segmentation fault
deferred.Resolve(Napi::String::New(Env(), hashResult));
}
void HashAsyncWorker::OnError(Napi::Error const &error) {
deferred.Reject(error.Value());
}