有什么方法可以让这个函数同步,或者在完成后添加一个回调函数来运行?
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;
};
答案 0 :(得分: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);
}
并调用代码:
dbGetLeagues(fb, function(leagues) {
console.log(leagues);
});