Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 509
Cod3Flu3nc3 Avatar asked Apr 17 '26 05:04

Cod3Flu3nc3


2 Answers

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}`)
});
like image 147
creativecreatorormaybenot Avatar answered Apr 19 '26 19:04

creativecreatorormaybenot


The database query is asynchronous and does not finish immediately. You need to use the promise return by admin.database().ref("users").once() to wait for the result of the query, and only send the response to the client after it succeeds. Currently, your response is sent to the client before the query completes.

Instead, put the response to the client inside the callback to the promise from once(), not outside:

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

Please read more about Firebase asynchronous APIs.

like image 37
Doug Stevenson Avatar answered Apr 19 '26 18:04

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!