Not able to figure out how to wait until forEach loop iterates completely and use that result












0















I am new to cloud functions (node js with typescript). I am using it to fetch data from Firebase database( as the code below). But Not able to figure out how to wait until forEach loop iterates completely and use that result.



  const reference = admin.database().ref('/books')
var path_key:string
var total_count:number = 0
reference .forEach(function (snapshot) {
path_key= snapshot(key).val()
ref_users_advance_bookings.child(path_key)
.once('value').then((snapshot2)=>{

if(condidtion met){
return response.send("failed")
}
else{
total_count++
}
)}

return true
})
// i want to use total_count value here
return response.send("count :"+total_count) // but every time I gets 0, as it get executed before forEach has ended
)}









share|improve this question

























  • What is ref? Please check how to create a minimal, complete, verifiable example.

    – Frank van Puffelen
    Nov 24 '18 at 23:04
















0















I am new to cloud functions (node js with typescript). I am using it to fetch data from Firebase database( as the code below). But Not able to figure out how to wait until forEach loop iterates completely and use that result.



  const reference = admin.database().ref('/books')
var path_key:string
var total_count:number = 0
reference .forEach(function (snapshot) {
path_key= snapshot(key).val()
ref_users_advance_bookings.child(path_key)
.once('value').then((snapshot2)=>{

if(condidtion met){
return response.send("failed")
}
else{
total_count++
}
)}

return true
})
// i want to use total_count value here
return response.send("count :"+total_count) // but every time I gets 0, as it get executed before forEach has ended
)}









share|improve this question

























  • What is ref? Please check how to create a minimal, complete, verifiable example.

    – Frank van Puffelen
    Nov 24 '18 at 23:04














0












0








0








I am new to cloud functions (node js with typescript). I am using it to fetch data from Firebase database( as the code below). But Not able to figure out how to wait until forEach loop iterates completely and use that result.



  const reference = admin.database().ref('/books')
var path_key:string
var total_count:number = 0
reference .forEach(function (snapshot) {
path_key= snapshot(key).val()
ref_users_advance_bookings.child(path_key)
.once('value').then((snapshot2)=>{

if(condidtion met){
return response.send("failed")
}
else{
total_count++
}
)}

return true
})
// i want to use total_count value here
return response.send("count :"+total_count) // but every time I gets 0, as it get executed before forEach has ended
)}









share|improve this question
















I am new to cloud functions (node js with typescript). I am using it to fetch data from Firebase database( as the code below). But Not able to figure out how to wait until forEach loop iterates completely and use that result.



  const reference = admin.database().ref('/books')
var path_key:string
var total_count:number = 0
reference .forEach(function (snapshot) {
path_key= snapshot(key).val()
ref_users_advance_bookings.child(path_key)
.once('value').then((snapshot2)=>{

if(condidtion met){
return response.send("failed")
}
else{
total_count++
}
)}

return true
})
// i want to use total_count value here
return response.send("count :"+total_count) // but every time I gets 0, as it get executed before forEach has ended
)}






node.js firebase firebase-realtime-database






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 23:07







Rakesh Kumar

















asked Nov 24 '18 at 21:29









Rakesh KumarRakesh Kumar

216




216













  • What is ref? Please check how to create a minimal, complete, verifiable example.

    – Frank van Puffelen
    Nov 24 '18 at 23:04



















  • What is ref? Please check how to create a minimal, complete, verifiable example.

    – Frank van Puffelen
    Nov 24 '18 at 23:04

















What is ref? Please check how to create a minimal, complete, verifiable example.

– Frank van Puffelen
Nov 24 '18 at 23:04





What is ref? Please check how to create a minimal, complete, verifiable example.

– Frank van Puffelen
Nov 24 '18 at 23:04












1 Answer
1






active

oldest

votes


















1














My guess is that you're trying to wait for a number of items to load from the database. For that you'll want to use Promise.all(), in something like:



var promises = ;
ref.forEach(function (snapshot) {
path_key= snapshot(key).val()
promises.push(ref_users_advance_bookings.child(path_key).once('value'));
});

Promise.all(promises).then(function(snapshots) {
var failed = false;
snapshot.forEach(function(snapshot2) {
if(condition met){
failed = true;
}
else {
total_count++;
}
)}
if (failed) {
return response.status(500).send("ERROR");
}
else {
return response.send("count :"+total_count);
}
});





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53462518%2fnot-able-to-figure-out-how-to-wait-until-foreach-loop-iterates-completely-and-us%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    My guess is that you're trying to wait for a number of items to load from the database. For that you'll want to use Promise.all(), in something like:



    var promises = ;
    ref.forEach(function (snapshot) {
    path_key= snapshot(key).val()
    promises.push(ref_users_advance_bookings.child(path_key).once('value'));
    });

    Promise.all(promises).then(function(snapshots) {
    var failed = false;
    snapshot.forEach(function(snapshot2) {
    if(condition met){
    failed = true;
    }
    else {
    total_count++;
    }
    )}
    if (failed) {
    return response.status(500).send("ERROR");
    }
    else {
    return response.send("count :"+total_count);
    }
    });





    share|improve this answer




























      1














      My guess is that you're trying to wait for a number of items to load from the database. For that you'll want to use Promise.all(), in something like:



      var promises = ;
      ref.forEach(function (snapshot) {
      path_key= snapshot(key).val()
      promises.push(ref_users_advance_bookings.child(path_key).once('value'));
      });

      Promise.all(promises).then(function(snapshots) {
      var failed = false;
      snapshot.forEach(function(snapshot2) {
      if(condition met){
      failed = true;
      }
      else {
      total_count++;
      }
      )}
      if (failed) {
      return response.status(500).send("ERROR");
      }
      else {
      return response.send("count :"+total_count);
      }
      });





      share|improve this answer


























        1












        1








        1







        My guess is that you're trying to wait for a number of items to load from the database. For that you'll want to use Promise.all(), in something like:



        var promises = ;
        ref.forEach(function (snapshot) {
        path_key= snapshot(key).val()
        promises.push(ref_users_advance_bookings.child(path_key).once('value'));
        });

        Promise.all(promises).then(function(snapshots) {
        var failed = false;
        snapshot.forEach(function(snapshot2) {
        if(condition met){
        failed = true;
        }
        else {
        total_count++;
        }
        )}
        if (failed) {
        return response.status(500).send("ERROR");
        }
        else {
        return response.send("count :"+total_count);
        }
        });





        share|improve this answer













        My guess is that you're trying to wait for a number of items to load from the database. For that you'll want to use Promise.all(), in something like:



        var promises = ;
        ref.forEach(function (snapshot) {
        path_key= snapshot(key).val()
        promises.push(ref_users_advance_bookings.child(path_key).once('value'));
        });

        Promise.all(promises).then(function(snapshots) {
        var failed = false;
        snapshot.forEach(function(snapshot2) {
        if(condition met){
        failed = true;
        }
        else {
        total_count++;
        }
        )}
        if (failed) {
        return response.status(500).send("ERROR");
        }
        else {
        return response.send("count :"+total_count);
        }
        });






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 24 '18 at 23:09









        Frank van PuffelenFrank van Puffelen

        239k29382409




        239k29382409
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53462518%2fnot-able-to-figure-out-how-to-wait-until-foreach-loop-iterates-completely-and-us%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin