我想从我的异步插件函数中调用 nodejs 回调。我已经看到了同步示例(此处),并且我正在使用一个出色的异步示例(此处)作为起始基础。
但是,当我尝试执行一个给 c++ AsyncWorker 子类的回调时,我得到一个分段错误。
这是我的代码:
#include <nan.h>
#include <functional>
#include <iostream>
#include <exception>
using namespace Nan;
using namespace v8;
using namespace std;
class ScriptWorker : public AsyncWorker {
public:
ScriptWorker(Callback *callback, const std::map<std::string, Callback*>)
: AsyncWorker(callback), script(script), cbs(cbs) {}
~ScriptWorker() {}
void Execute () {
// ------------------------
// Segmentation fault after
// ------------------------
Local<Value> argv[] = {
New<v8::Number>(id)
};
// -------------------------
// Segmentation fault before
// -------------------------
cbs["getUser"]->Call(1, argv);
}
private:
std::string script;
std::map<std::string, Callback*> cbs;
};
NAN_METHOD(Method) {
Local<Object> array = info[0]->ToObject();
Callback *callback = new Callback(info[1].As<Function>());
// Build up callbacks passed in from javascript.
// Will be a dynamic loop, but for now, hard code the one getUser example.
std::map<std::string, Callback*> cbs;
cbs.insert(std::pair<std::string, Callback*>("getUser",
new Callback(
array->Get(
v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), "getUser")
).As<Function>()
)
));
AsyncQueueWorker(new ScriptWorker(callback, cbs));
}
NAN_MODULE_INIT(Init) {
Nan::Set(target, Nan::New<String>("hello").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(Method)).ToLocalChecked());
}
NODE_MODULE(hello, Init)
我的问题:
- 我不应该使用 Nan 的 AsyncWorker 而是自己动手吗?
- 如何设置 Execute 函数以调用 Javascript?