return javascript variable from inside callback function

I am trying to get client.get to return the reply value so it can be used globally.It keeps saying undefined.any suggestions

var redis = require("redis");
var websocket= require("websocket");
var valuewanted;
websocket.on('message', function(data) {

 if (data.type == "purchase" && data.price > 0) {

  console.log("==========================================================");
  console.log(data );
  console.log("==========================================================");

client.get(p1, function(err, reply) {
        var valuewanted = reply;
            console.log(reply);
        });  
});

the console.log logs the value but if i try to log valuewanted it doesnt work.

1 answer

  • answered 2017-11-12 19:38 bozdoz

    Drop the var within the client.get function:

    client.get(p1, function(err, reply) {
      // valuewanted already defined above
      valuewanted = reply;
      console.log(reply);
    });  
    

    If you use var within a function, it becomes scope-blocked to that function.

    From mozilla:

    The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.

    In this case, using var within that function redefines it within that function, and its scope becomes "the enclosing function". Hope this helps.