-1

I have a callback function and within that, a for loop containing another calllback.

I am struggling with understanding the variable scope. I need to access the out variable throughout the nested structure:

var out = {"foo":123};

persistence.getAllApiKeys(function(err, allKeys){

  for (var prop in allKeys) {

    out = {"baz":456};

      persistence.getApiKeyValue("test", function(err2, value) {

        out = {"success":true}; // <--does not update

      });
  }

    console.log(out);
})

Outputs:

{ baz: 456 }

How can I access the out variable inside the final callback? i.e. set it to "success":true?

Ben
  • 6,026
  • 11
  • 51
  • 72
  • `getApiKeyValue` function is asynchronous, at the moment, when you call `console.log(out);` the second call is most likely waiting for a response from API, so `out = {"success":true};` assignment will be executed later. – halfzebra Jul 19 '15 at 16:37
  • Async, async, async. When you understand asynchronous callbacks and the fact that they run some time LATER, then you will understand why your `out` variable is not set yet when you're logging it. Your issue has nothing to do with scope and everything to do with the timing of your async callbacks. You can only use async results INSIDE the callback that signals their completion. You can read this for more info: [How to return response from ajax call](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). – jfriend00 Jul 19 '15 at 16:38

1 Answers1

0

Classic aysnc. console.log is executed before the callback for getApiKeyValue. Put the console inside the callback and you will see what's wrong.

Swaraj Giri
  • 4,007
  • 2
  • 27
  • 44