Roman Melnyk
Roman Melnyk

Reputation: 190

Get data from nested foreach

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); // {}

});

};

Upvotes: 0

Views: 481

Answers (1)

dan
dan

Reputation: 1984

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

});

...

Upvotes: 1

Related Questions