0

I'm building an app using firebase and Node.js. I need to get data from nested foreach. How to do it correctly? Need to return the results of all iterations simultaneously.

exports.userParty = function (userInfo, cb) {

var userID = userInfo.userID;
var clubID = userInfo.clubID;

var refUserParty = ref.child(userID).child('my_party_id');

var party = {};

refUserParty.orderByValue().once("value", function (snapshot) {

    var party = {};

    snapshot.forEach(function (partyID) {

        var refParty = dbb.ref('clubs').child(clubID).child('party').child(partyID.val());

        refParty.once('value', function (partyBody) {
            party[partyID.val()] = partyBody.val();
            //console.log(party);
        });

    });
    cb(party); // {}

});

};
Roman Melnyk
  • 180
  • 2
  • 16
  • What are you trying to do? Call the callback with the `partyBody` object within the `refParty.once(...` block? – dan Jun 06 '17 at 08:29
  • If so, you should move `cb(party)` to the line where you currently have `//console.log(party)` – dan Jun 06 '17 at 08:32
  • In this case, I get only the first iteration result. I need to return the results of all iterations simultaneously. – Roman Melnyk Jun 06 '17 at 08:39
  • Ah, ok. This should help - https://stackoverflow.com/a/18983245/4774345 – dan Jun 06 '17 at 08:40

1 Answers1

1

You need to call the callback after all the async functions in the forEach block have completed. You can do this using a simple counter to check all async functions are complete:

...

let completedSnapshots = 0;

snapshot.forEach(function (partyID) {

    var refParty = dbb.ref('clubs').child(clubID).child('party').child(partyID.val());

    refParty.once('value', function (partyBody) {
        party[partyID.val()] = partyBody.val();
        completedSnapshots++;
        if (completedSnapshots === snapshot.val().length) {
            cb(party);
        }
    });

});

...
dan
  • 1,944
  • 1
  • 15
  • 22