最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get synchonous data in firebase? - Stack Overflow

programmeradmin1浏览0评论

Is there any way I can make this function synchronous, or add a callback function to run when it's finished?

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;
};

Is there any way I can make this function synchronous, or add a callback function to run when it's finished?

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;
};
Share Improve this question edited Jan 9, 2014 at 14:27 Viktor Sehr asked Jan 9, 2014 at 14:17 Viktor SehrViktor Sehr 13.1k6 gold badges62 silver badges95 bronze badges 2
  • 1 Why would you want to? Generally, making an async function synchronous is not the answer (but in some cases there are, so I'm curious) – tymeJV Commented Jan 9, 2014 at 14:24
  • 1 Actually, I just want to run code when all the leagues are fetched, a callback would be good to. – Viktor Sehr Commented Jan 9, 2014 at 14:28
Add a ment  | 

1 Answer 1

Reset to default 10

Just include a callback & Run if after your 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);
}

And call the code like:

dbGetLeagues(fb, function(leagues) {
    console.log(leagues);
});
发布评论

评论列表(0)

  1. 暂无评论