【问题标题】:How to get synchonous data in firebase?如何在firebase中获取同步数据?
【发布时间】:2014-01-09 14:17:48
【问题描述】:

有什么方法可以让这个函数同步,或者添加一个回调函数在它完成时运行?

var fbGetLeagues = function(fb) {
  var leagues = [];
  fb.child('leagues').once('value', function(snapshot) {
    snapshot.forEach(function(child) {
      var id = child.name();
      var name = child.child('name').val();
      leagues.push({'id': id, 'name': name});
    });
  });
  return leagues;
};

【问题讨论】:

  • 您为什么要这样做?一般来说,使异步函数同步不是答案(但在某些情况下有,所以我很好奇)
  • 其实我只是想在获取所有联赛的时候运行代码,回调就好了。

标签: javascript firebase


【解决方案1】:

如果在您的forEach 之后,只需包含一个回调并运行:

var dbGetLeagues = function(fb, callback) {
    snapshot.forEach(function(child) {
      var id = child.name();
      var name = child.child('name').val();
      leagues.push({'id': id, 'name': name});
    });
    callback(leagues);
}

并像这样调用代码:

dbGetLeagues(fb, function(leagues) {
    console.log(leagues);
});

【讨论】:

  • 但是console.log的insteam我如何存储在一个变量中。
  • 每当我尝试像这样存储var extvar; dbGetLeagues(fb, function(leagues) { console.log(leagues);extvar = leagues }); console.log(extvar);时,我都会得到未定义的值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多