我AsyncWorker
用来运行异步任务。问题是我有很多任务要一个接一个地运行,而且顺序很重要。为了保持秩序,我使用排队技术来确保AsyncWorker
对象是按莱特顺序创建的,只有在每个任务完成后。我将回调存储在 avector<Function>
中,并将其传递给AsyncWorker
,但出现以下错误:
# Fatal error in v8::HandleScope::CreateHandle()
# Cannot create a handle without a HandleScope
还有其他方法可以解决这个问题吗?我也尝试过使用Napi::Persistent
,但我无法将Napi::FunctionReference
变量传递给AsyncWorker
调用者函数:
Napi::Value BlockChainWrapper::genesis(const Napi::CallbackInfo& info) {
std::lock_guard<std::mutex> guard_ready_queue(ready_queue_mutex);
this->ready_queue_callback.push_back(info[1].As<Napi::Function>());
this->ready_queue_data.push_back(info[0].As<Napi::Object>());
this->ready_queue_func.push_back(BlockChainWrapperTypes::_genesis_ready);
this->ready_queue_env.push_back(info.Env());
return info.Env().Undefined();
}
void BlockChainWrapper::genesis_ready() {
AsyncBlockChainFunctions* asyncWorker = new AsyncBlockChainFunctions(this->ready_queue_callback.front(), 0, blockchain_obj, this->ready_queue_data.front());
asyncWorker->Queue();
}
AsyncWorker 构造函数:
AsyncBlockChainFunctions::AsyncBlockChainFunctions(Napi::Function& callback, int mode, std::shared_ptr<BlockChain> _blockchain, Napi::Object& resource) : AsyncWorker(callback), mode(mode) {};
编辑 1 我实现了 PromiseWorker,但仍然遇到这些错误:BlockChainWrapper 继承 ObjectWrap。
Napi::Object BlockChainWrapper::Init(Napi::Env env, Napi::Object exports) {
Napi::HandleScope scope(env);
Napi::Function func = DefineClass(env, "BlockChainWrapper", {
InstanceMethod("genesis", &BlockChainWrapper::genesis)
});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
exports.Set("BlockChainWrapper", func);
return exports;
}
# Fatal error in HandleScope::HandleScope
# Entering the V8 API without proper locking in place
修改 AsyncWorker 构造函数、类和解析函数:
class AsyncBlockChainFunctions : public PromiseWorker
AsyncBlockChainFunctions(Napi::Promise::Deferred const &d, std::shared_ptr<BlockChain> _blockchain, int mode, Napi::Object& resource) : PromiseWorker(d), mode(mode) {}
void Resolve(Napi::Promise::Deferred const &deferred) {
deferred.Resolve(Napi::String::New(deferred.Env(), this->block_as_json_string));
};
调用函数:
Napi::Value BlockChainWrapper::genesis(const Napi::CallbackInfo& info) {
std::lock_guard<std::mutex> guard_ready_queue(ready_queue_mutex);
this->ready_queue_data.push_back(info[0].As<Napi::Object>());
this->ready_queue_func.push_back(BlockChainWrapperTypes::_genesis_ready);
this->ready_queue_env.push_back(info.Env());
Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(info.Env());
std::cout << "genesis" << std::endl;
return deferred.Promise();
}
从另一个队列管理线程调用 Genesis 就绪
void BlockChainWrapper::genesis_ready() {
Napi::Env env = ready_queue_env.front();
Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env);
Napi::Object input_obj = this->ready_queue_data.front().As<Napi::Object>();
auto *x = new AsyncBlockChainFunctions(std::ref(deferred), this->blockchain_obj, 0, input_obj);
x->Queue();
}