0

I've got a problem while programming some functions for Firebase functions. I want to find the User with the highest value stored in PFM and save his name in a Variable but the Variable does not change. What am I doing wrong?

Here is my Code:

var highestPFM = 0;
var userToSend = "";    

db.collection("users").get().then((snapshot) => {
        snapshot.forEach((doc) => {
        var data = doc.data();
            if(highestPFM > data["pfm"]){
                highestPFM = data["pfm"];
                userToSend = doc.id;
            }
        });
        console.log(prefixSendBottle + "User with highest PFM: " + userToSend);
        return userToSend;
    }).catch((err) => {
        response.send(err);
        console.log(err);
    });
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • @zero298 I don't think OP's issue is related to Async code. It's just a logical error in code. Plz check my answer. – Vivek Athalye Apr 03 '18 at 18:30
  • @VivekAthalye I don't know, I worry anytime I see a variable have a scope broader than the scope of the asynchronous scope. Maybe it isn't related, but I'd like to see how `highestPFM` is used after the call to firebase. No matter what, we need more context. – zero298 Apr 03 '18 at 18:31
  • @zero298 Yes, I can understand your concern and I agree with you on that. :) – Vivek Athalye Apr 03 '18 at 18:33
  • While the scope of the variable could indeed be limited to the callback, that is not the cause of the problem here. I vote to reopen. – Frank van Puffelen Apr 03 '18 at 19:15

1 Answers1

2

You are checking if(highestPFM > data["pfm"]){... assuming you have only +ve values for pfm, this condition will never be true and hence the value of highestPFM will never change.

You need to change the condition to if(data["pfm"] > highestPFM){.

Vivek Athalye
  • 2,974
  • 2
  • 23
  • 32