如何在firebase中获取同步数据?

Vik*_*ehr 4 javascript firebase

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

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;
};
Run Code Online (Sandbox Code Playgroud)

tym*_*eJV 9

只需在您的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);
}
Run Code Online (Sandbox Code Playgroud)

并调用代码如:

dbGetLeagues(fb, function(leagues) {
    console.log(leagues);
});
Run Code Online (Sandbox Code Playgroud)