0

I´ve checked numerous posts but could not solve the issue. I want to return the array before going on. I tried using a function with a callback but that did not work either.

My code looks as following:

exports.GetHelmets = functions.database.ref('onTrack/{userID}').onCreate(event => {
var helmets = [];

let userID = event.params.userID;

let friendRef = admin.database().ref("friends").child(userID);
friendRef.once("value").then(snapshot => {
    snapshot.forEach(function(snapshot2){
        let rider = snapshot2.val();
        let riderID = rider.id;

        let rhRef = admin.database().ref("User").child(riderID);
        rhRef.once("value", function(snapshot3){

            let rider2 = snapshot3.val();
            let helmetID = rider2.helmet;

        if (helmetID != "STANDARD"){
            if(helmets.indexOf(helmetID) < 0){
                helmets.push(helmetID);
            };
        };
    });
});
    return helmets;
}).then(helmets => {

    //WORK WITH ARRAY
});

I hope you can help me, thanks!

1 Answer 1

1

You want the last then() to get all the inner data, each of which requires its own call to once(). In such a case, you'll want to use Promise.all() to wait for all the onces.

exports.GetHelmets = functions.database.ref('onTrack/{userID}').onCreate(event => {
let userID = event.params.userID;

let friendRef = admin.database().ref("friends").child(userID);
friendRef.once("value").then(snapshot => {
    var promises = []l
    snapshot.forEach(function(snapshot2){
        let rider = snapshot2.val();
        let riderID = rider.id;

        let rhRef = admin.database().ref("User").child(riderID);
        promises.push(rhRef.once("value");
      });
    });
    return Promise.all(promises);
}).then(snapshots => {
    var helmets = [];

    snapshots.forEach((snapshot) => {
        let rider2 = snapshot.val();
        let helmetID = rider2.helmet;

        if (helmetID != "STANDARD"){
          if(helmets.indexOf(helmetID) < 0){
            helmets.push(helmetID);
          };
        };
    });
    // WORK WITH helmets
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.