0

I'm using Firebase to access to same data, but i can't use the data out of the function used to access it. How i can make a console log of the data just accessed instead of the initial value?

var whatNeed = 'hello';
gameData = new Firebase('https://thegame.firebaseio.com/gameData');
    gameData.on("value", function(snapshot) {
        var data = snapshot.val();
        whatNeed = data.property;
    });
console.log(whatNeed);
ruggero
  • 35
  • 3
  • Call console.log() within the callback, if you can. – Aweary Dec 14 '14 at 21:56
  • See (a.o) http://stackoverflow.com/questions/25697907/javascript-assigning-value-to-variable-from-callback-return-timing/25700838#25700838 and http://stackoverflow.com/questions/25677977/asynchronous-callback-returns-null/25684264#25684264 for an explanation of this behavior in the context of Firebase. Since the problem is not specific to Firebase, you can also read these more generic answers: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call/14220323#14220323 and http://stackoverflow.com/questions/23667086/ – Frank van Puffelen Dec 14 '14 at 23:14

1 Answers1

0

whatNeed will always contain the initial value when called outside of your callback as the console.log will be called first since the value event handler is asynchronous.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81