Angularfire有一个方便的.$loaded()
回调,当您的数据已解决时会触发该回调。
我正在尝试在NodeJS应用程序中实现类似的功能。
使用我目前的代码,并非所有数据都在正确的时间或正确的顺序得到解决:
doWeeklySummary: function () {
var users = [];
firebase.usersRef().once('value', function (userSnapshot) {
userSnapshot.forEach(function (user) {
var events = [];
console.log('events for ' + user.val().name)
module.exports.getUserEvents(user.key(), function (response) {
for (var x = 0; x < response.length; x++) {
module.exports.getEvent(response[x], function (event) {
events.push(event);
})
}
});
//Send event email summary to user
console.log(user.val().name + ' has ' + events.length + ' events');
console.log(events);
});
console.log('all done')
});
},
getUserEvents: function (userId, callback) {
firebase.userEventsRef(userId).on('value', function (snapshot) {
var events = [];
snapshot.forEach(function (childSnapshot) {
var promise = firebase.eventRef(childSnapshot.key()).once('value', function (snap) {
return snap.val();
});
events.push(childSnapshot.key());
});
callback(events);
});
},
getEvent: function (eventId, callback) {
firebase.eventRef(eventId).once('value', function (snap) {
callback(snap.val());
});
}
但是,这将按以下顺序返回数据:
events for User 1
User 1 has 0 events
[]
events for User 2
User 2 has 0 events
[]
events for User 3
User 3 has 0 events
[]
all done
...
所需的输出类似于:
events for User 1
User 1 has 1 events
[{name: event 1}]
events for User 2
User 2 has 2 events
[{name: event 1}, {name: event 2}]
events for User 3
User 3 has 1 events
[{name: event 3}]
all done