的文档AsyncContext
有这个同步工作的示例(仅稍作修改,但仍然有效):
#include "napi.h"
void MakeCallbackWithAsyncContext(const Napi::CallbackInfo& info)
{
Napi::Function callback = info[0].As<Napi::Function>();
Napi::Object resource = info.Env().Global().As<Napi::Object>();;
Napi::AsyncContext context(info.Env(), "async_context_test", resource);
callback.MakeCallback(Napi::Object::New(info.Env()),
std::initializer_list<napi_value>{}, context);
}
我想知道如何异步使用它 - 这是我最新的镜头:
Napi::AsyncContext* _context;
Napi::FunctionReference* _callback;
Napi::Object* _resource;
void CallBack()
{
_callback->MakeCallback(*_resource, std::initializer_list<napi_value>{}, *_context);
}
void MakeCallbackWithAsyncContext(const Napi::CallbackInfo& info)
{
Napi::Function cb = info[0].As<Napi::Function>();
_callback = new Napi::FunctionReference(Napi::Persistent(cb));
_callback->SuppressDestruct();
_resource = new Napi::ObjectReference(Napi::Persistent(env.Global()));
_resource->SuppressDestruct();
_context = new Napi::AsyncContext(info.Env(), "async_context_test", _resource->Value());
// run CallBack() in different thread
}
程序内部崩溃CallBack()
。