0

I want to access and use a firebase db child across my whole javascript file.

This is how my db looks like:

  var bidAUDUSD;
  var audusd = firebase.database().ref('Symbols/AUDUSD/bid').once('value')
.then(function(snapshot){
      bidAUDUSD = snapshot.val();
      console.log(bidAUDUSD); // this prints the bid;
    });
 console.log(bidAUDUSD); //this prints undefined;

Any ideas how can I use it globally? Thanks in advance!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Radu Serse
  • 81
  • 9

1 Answers1

1

"then" promise will take sometime to print the snapshot, but in your case you printed the global variable before the "then" is called. So what you can do is call a function inside the "then" promise and then try print the global variable like I coded below.

var bidAUDUSD;
var audusd = firebase.database().ref('Symbols/AUDUSD/bid').once('value')
.then(function(snapshot){
  bidAUDUSD = snapshot.val();//"then" promise will take some time to execute, so only the bidAUDUSD is undefined in the outside console log. 
// what you can do is call a function inside the "then" promise and then print the console log like below. 
  _callConsoleLog(bidAUDUSD);
  console.log(bidAUDUSD); // this prints the bid;
});

var _callConsoleLog=function(bidId){
   // try to print it here. 
   console.log(bidId)// either you can print the parameter that is passed or
   console.log(bidAUDUSD) // your global variable.
}
MuruGan
  • 1,402
  • 2
  • 11
  • 23