Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get synchonous data in firebase?

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;
};
like image 446
Viktor Sehr Avatar asked Dec 26 '22 15:12

Viktor Sehr


1 Answers

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);
});
like image 95
tymeJV Avatar answered Dec 28 '22 06:12

tymeJV