0

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.

4
  • 2
    You redefine var valuewanted inside get callback so it is different valuewanted which is local to the function. Commented Nov 12, 2017 at 19:35
  • what would be the right way to do it ? Commented Nov 12, 2017 at 19:36
  • 1
    Check if function(err, reply) should (is expected to) return a value. Commented Nov 12, 2017 at 19:36
  • 1
    remove var. Just valuewanted = reply;. In any case you can operate it only inside callback. Do not expect return valuewanted;. Commented Nov 12, 2017 at 19:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.