1

Angularfire has a handy .$loaded() callback, which is fired when your data has resolved.

I'm trying to achieve something similar in a NodeJS application.

With the code I have currently, not all of the data is resolved at the correct time, or in the right order:

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

However, this returns the data in the following order:

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
...

The desired output is something like:

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
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
MNelmes
  • 124
  • 2
  • 19
  • You'll want to use `Promise.all()` to wait for all data to be loaded. Have a look at Bergi's answer here for a great example: https://stackoverflow.com/questions/35879695/promise-all-with-firebase-datasnapshot-foreach. For more answers, see: https://www.google.com/search?q=site:stackoverflow.com+firebase+promises.all – Frank van Puffelen Dec 09 '17 at 15:54
  • 1
    Thanks, I did see Bergi's answer and have struggled to implement the Promise.all as I do not know where it should go? I've tried various places with not luck – MNelmes Dec 09 '17 at 16:07

0 Answers0