I have a node server which makes a call to an external module. My problem is that I need the data return by the call to the module but node (which is non-blocking) simply isn't waiting for the return value. Any solution to this ?
Code :
Server.js
var value = module.functionA(param);
console.log("Message one %s", value);
Module.js
function callToFunctionInModule(param){
console.log("In func");
return param+2;
}
exports.functionA = function(param){
console.log("Message two");
var returnVal = callToFunctionInModule(param);
return returnVal;
};
Ouput
Message two
Message one undefined
In func
Is there anyway to get the following output (waiting to get the return value from the module WITHOUT using callback in the line var value = module.functionA(param);
First thing, the code you gave (sync) doesn't represent the actual situation (async). What you should do in the case you want to deal with async stuff is use callbacks. That's the whole idea behind node.js - event-driven*ness*.
Server.js
module.functionA(param, function(val) {
console.log("Message one %s", val);
});
Module.js
function callToFunctionInModule(param, cb) {
console.log("In func");
/* some db query */
not_so_magical_async_stuff("blah", function(/* value passed as argument */) {
cb(param + 2 /* or the value passed as an argument to this function */);
}
}
exports.functionA = function (param, cb) {
console.log("Message two");
callToFunctionInModule(param, cb);
};
Now, what happens is this:
Function passed to functionA
is passed on to callToFunctionInModule
, which calls it back with the returned value as an argument. The result: non-blocking beautiful code! Trust me, once you get hooked into this async thingy, you'll love it!