简体   繁体   中英

Firebase Cloud Functions - Synchronous Functions

I´m new to firebase cloud functions. I want to create my index.js as following:

exports.countFruits = functions.database.ref("fruits/{FruitID}").onWrite(event =>{

(...)

    var sauces = [];

    let ref = admin.database().ref("sauces");
    ref.on("child_added", function(snapshot, prevChildKey){

    let sauce = snapshot.val();
    sauces.push(sauce.id);
    });

// -> USE THE COMPLETED ARRAY FOR NEXT ANOTHER PURPOSE

});

So my Problem is, that I want to use the COMPLETED array while it is actually being filled. As a consequence I want to structure my code synchronously so the next function is only executed when all sauce.id are in the array.

How can I code that?

Thank you!

When you listen to child_added events, your handler will be called for each existing child and any time a child is added later. So there is no clear moment when all children have been processed.

If you want to handle all current children, you should use a once("value" handler, like this:

exports.countFruits = functions.database.ref("fruits/{FruitID}").onWrite(event =>{

(...)

    var sauces = [];

    let ref = admin.database().ref("sauces");
    ref.once("value", function(snapshot){
      snapshot.forEach(function(sauceSnapshot) {
        let sauce = snapshot.val();
        sauces.push(sauce.id);
      });
      // -> USE THE COMPLETED ARRAY FOR NEXT ANOTHER PURPOSE
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM