return a js object from a javascript function that is called from a node cpp addon

151 views Asked by At

I am tyring to create and return a javascript function object from a function that is called from a c++ node addon. The object was getting created, but wasn't getting returned by the function.

callback function that creates an object named cursor

var callback_fn = function(record){
    var res = new cursor(records);//functionalities of res(created here are working here when tested inside callback_fn but its not getting returned)
    return res;//not only object, nothing was getting returned.I even tried returning a dummy var.

}

Node addon snippet that calls the "callback_fn"(its in the args[1])

//Isolate* isolate = Isolate::GetCurrent();
//HandleScope scope(isolate);
Local<Object> obj= Object::New(isolate);
obj->Set(String::NewFromUtf8(isolate,"name"),Integer::New(isolate,custnum));
obj->Set(String::NewFromUtf8(isolate,"address"),Integer::New(isolate,custnum));//integer is assigned to name and address just for testing.
obj->Set(String::NewFromUtf8(isolate,"custnum"),Integer::New(isolate,custnum));
Local<Function> cb = Local<Function>::Cast(args[1]);
Local<Value> argv[1] = {obj};
cb->Call(isolate->GetCurrentContext()->Global(), 1, argv);  
1

There are 1 answers

0
Puneeth Manyam On BEST ANSWER

The mistake in the code is that the javascript function "callback_fn" is returning the object to the cpp addon. So, we need to store it in the cpp addon and return it a callback is to be implemented.

ret_val = cb->Call(isolate->GetCurrentContext()->Global(), 1, argv); 
//where ret_val is defined as Local<value> ret_val;
args.GetReturnValue().Set(ret_val);

In javscript ican be stored and returned.

var res_final=addon.addonfunction(input to addon);
return res_final;

If the cpp addon that was written wasn't asynchronous we can store the res a separate var in the node program and return it after the addon.addonfunction(input to addon) was finished executing(since everything goes in sequence in a synchronous program).