3

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?

2 Answers 2

3

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}`)
});
Sign up to request clarification or add additional context in comments.

Comments

3

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.

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.