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?
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
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}`)
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With