Ad

HTTP Function Return Initial Array Values

I've got this firebase cloud function that I've coded to count the number of registered users vs the anynymous users.

// Recalc totals user 
exports.recalcTotalUsers = functions.https.onRequest((req, res) => {
    var arr = {
        anonymous: 0,
        registered: 0
    };

    console.log('starting recalcTotalUsers');
    admin.database().ref("users").once("value").then((snapshot) => {
        snapshot.forEach(function (uid) {
            if (uid.child('/email').val() == ANONYMOUS_STRING) {
                arr.anonymous++;
            } else {
                arr.registered++;
            }
            console.log(`1. ${arr.anonymous}:${arr.registered}`)
        })
    });
    res.status(200).send(`ok registered: ${arr.registered}, anonymous: ${arr.anonymous}`)  
 });

When the function returns I get alway anonymous = 0 and registered = 0 event if they have different values... what I am doing wrong?

Ad

Answer

You have to move your response! Because at the moment, let's look at your code:

admin.database().ref("users").once("value").then((snapshot) => {
    snapshot.forEach(function (uid) {
        if (uid.child('/email').val() == ANONYMOUS_STRING) {
            arr.anonymous++;
        } else {
            arr.registered++;
        }
        console.log(`1. ${arr.anonymous}:${arr.registered}`)
    })
});
res.status(200).send(`ok registered: ${arr.registered}, anonymous: ${arr.anonymous}`)

As you might know, the database functions are all asynchronous, which means that they

  • take time to be executed
  • have promises and thus do not wait before the next line of code is executed

    res.status(200).send(ok registered: ${arr.registered}, anonymous: ${arr.anonymous})

That line is executed before you query through your "users" snapshot. You have to move it, and best practice would be another promises (.then(...)), but you can just do it like this:

admin.database().ref("users").once("value").then((snapshot) => {
    snapshot.forEach(function (uid) {
        if (uid.child('/email').val() == ANONYMOUS_STRING) {
            arr.anonymous++;
        } else {
            arr.registered++;
        }
        console.log(`1. ${arr.anonymous}:${arr.registered}`)
    })
    res.status(200).send(`ok registered: ${arr.registered}, anonymous: ${arr.anonymous}`)
});
Ad
source: stackoverflow.com
Ad