从node.js本地代码调用回调 [英] Calling callback from node.js native code
问题描述
我使用c ++为node.js编写一个附件。
I'm writing an add-on for node.js using c++.
这里有一些代码片段:
class Client : public node::ObjectWrap, public someObjectObserver {
public:
void onAsyncMethodEnds() {
Local<Value> argv[] = { Local<Value>::New(String::New("TheString")) };
this->callback->Call(Context::GetCurrent()->Global(), 1, argv);
}
....
private:
static v8::Handle<v8::Value> BeInitiator(const v8::Arguments& args) {
HandleScope scope;
Client* client = ObjectWrap::Unwrap<Client>(args.This());
client->someObject->asyncMethod(client, NULL);
return scope.Close(Boolean::New(true));
}
static v8::Handle<v8::Value> SetCallback(const v8::Arguments& args) {
HandleScope scope;
Client* client = ObjectWrap::Unwrap<Client>(args.This());
client->callback = Persistent<Function>::New(Handle<Function>::Cast(args[0]));
return scope.Close(Boolean::New(true));
}
我需要保存一个javascript函数作为回调函数调用它。
Client类是另一个对象的观察者,javascript回调应该从onAsyncMethodEnds调用。
不幸的是,当我调用函数BeInitiator时,我在回调之前收到Bus error:10错误Call()
I need to save a javascript function as callback to call it later. The Client class is an observer for another object and the javascript callback should be called from onAsyncMethodEnds. Unfortunately when I call the function "BeInitiator" I receive "Bus error: 10" error just before the callback Call()
>
推荐答案
您不能从另一个线程 - >调用
。 JavaScript和Node是单线程的,试图从另一个线程调用一个函数等于试图一次运行两个线程的JS。
You cannot ->Call
from another thread. JavaScript and Node are single threaded and attempting to call a function from another thread amounts to trying to run two threads of JS at once.
你应该重新工作你的代码不要这样做,或者你应该阅读 libuv
的线程库。它提供 uv_async_send
,可用于在单独的线程中触发主JS循环中的回调。
You should either re-work your code to not do that, or you should read up on libuv
's threading library. It provides uv_async_send
which can be used to trigger callback in the main JS loop from a separate thread.
docs here: http://nikhilm.github.io/uvbook/threads.html
There are docs here: http://nikhilm.github.io/uvbook/threads.html
这篇关于从node.js本地代码调用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!