本文介绍了javascript中的Firebase全局访问子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的整个javascript文件中访问并使用firebase db子级.

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!

推荐答案

"then"许诺将花费一些时间来打印快照,但是在您的情况下,您在调用"then"之前就打印了全局变量.因此,您可以做的是在"then" promise内调用一个函数,然后尝试打印全局变量,如我在下面的代码所示.

"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.
}

这篇关于javascript中的Firebase全局访问子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 06:17