0

I am not able to modify the value of outputString variable inside callback.

var outputString;

    client.get(key,function(err,value){

                        outputString = "key="+key+" value="+value ;
                        console.log(outputString);

                    })

console.log(outputString);

When I print the value of outputString, it says "undefined"

Zack
  • 2,078
  • 10
  • 33
  • 58
  • is `key` defined? Is `value` returning something? Check `if(err)` – Max Oct 24 '15 at 18:47
  • Worth reading this: [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). This is one of the most common points of confusion about Javascript and asynchronous operations. – jfriend00 Oct 24 '15 at 18:56
  • @jfriend00 Okay. So the control comes back to console.log immediately.So I cannot see the modified value of the variable. So it is not possible to achieve what I am trying to do. I mean accessing a variable before it is updated. But I think this would work if I put a timer . I wait for sometime before printing the variable – Zack Oct 24 '15 at 19:08
  • If you read the answers for the question yours was marked a dup of, it gives you several alternatives. A timer is a bad choice because it assumes that it knows how long the async operation is going to take. Please read the answers for the dup question. It is all spelled out there. Async operations REQUIRE asynchronous coding techniques. You cannot use synchronous coding techniques with asynchronous operations. If you're going to code in Javascript, you MUST get used to this and learn how to do it properly. – jfriend00 Oct 24 '15 at 19:10
  • @jfriend00 Yes. Thanks again for your inputs. – Zack Oct 24 '15 at 19:10

1 Answers1

0

client.get() returns immediately, so outputString hasn't been set when the last console.log() is called. The callback function isn't called until sometime later.

  • no. that is the purpose of callback. I am setting the value of variable in callback so that it gets modified before the control comes out of the client.get method – Zack Oct 24 '15 at 18:56
  • Okay. I think you are right. Let me do some more analysis and then I will mark the answer. Thanks. – Zack Oct 24 '15 at 19:09