Karma Doe Karma Doe - 1 year ago 69
Node.js Question

How do i use a value from a function in another as a callback? Node js

I´ve been making a prototype of webservice and I get confronted with the following problem: Whenever I try to use a 'var' as a callback i get: undefined.

What I'm tryng to do is:

var mysqlquery = function (){
var vAlue = XXX;
var service = function (pp, ee, cb){
var toReturn= ({ //XML code
Value: vAlue

Output should be XXX

The service runs fine and logs the values, but when i try to make it a callback to respond it is undefined, I guess because of the async of node.
Already tried making it a global or global.window or calling it inside another function, none of wich work. I don´t want to use extra modules for this, is there any method for it ? (Also tried this.)
Any tip is much apreciated, thanks.

Answer Source

You already know that defining a var in a function limits its scope to that function, but you can pass that data out of the function using a return, like so:

var mysqlquery = function (){
   return 'XXX';

> "XXX"

What's happening in the console.log line is that your function is being evaluated, and returns "XXX", and then it is passed to console.log.

This is the foundation of callbacks: if you have an asynchronous function, you can pass a callback function into it to feed in the result of the async function:

function print(res) {

function asyncThing(cb) {
  var ten = 5 + 5
  window.setTimeout(cb.bind(this, ten), 5000)

... [wait five seconds]...
> 10
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download