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);
    });
4
  • @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. Commented Apr 3, 2018 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. Commented Apr 3, 2018 at 18:31
  • @zero298 Yes, I can understand your concern and I agree with you on that. :) Commented Apr 3, 2018 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. Commented Apr 3, 2018 at 19:15

1 Answer 1

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){.

Sign up to request clarification or add additional context in comments.

1 Comment

Ouh that was a really stupid mistake from me. That for the advice!

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.