Javascript Global Variables Unreachable From Outside an "IF-ELSE" Block

Hello Earthlings :slight_smile:

I have an interesting problem that I would very much appreciate help with. You what has gone and happened is this, I have created a method inside my lovely Class, the method’s job is to read an online database, Firebase’s CloudFireStore - yeah I’m also expecting a flaming phoenix to fly across the horizon every time I mention Firebase :slight_smile:

The method is getting the data as expected but, can write it to console, there is trouble in paradise when I try to reuse the variable outside of the “if-else” statement I am using to confirm the data, is this weird or what!!! I bet it’s what :slight_smile:

fireNewStudent(){

        let lastStudentNum = db.collection("control").doc("lastStudentNum");
        let StudentNum;

        lastStudentNum.get().then(function(doc){
            if (doc.exists){
                currentStudentNum = doc.data();
                StudentNum = currentStudentNum.lastStudentNum;
                console.log(StudentNum);
                // Prints expected result
            } else{
                // doc.data will be undefined in this case
                console.log("Error getting current student number");
            }
        }).catch(function (error) {
            console.log("Error getting document: ", error)
        });

        document.write(JSON.stringify(currentStudentNum));
        //Prints out an empty object  => {}

}

Thanks a bunch for having a look and hope to hear from you soon :slight_smile:

Can you include a screenshot of the exact console error message you’re getting?

I assume the get method is asynchronous, which is why you use the then. The then callback function is where you can use currentStudentNum. Put your document.write inside that function and it will work.

The code after the get call (below) still runs even though the data has not been retrieved back from the get yet. This is why you can an empty object when you try to stringify currentStudenNum.

document.write(JSON.stringify(currentStudentNum));

Randell, my man! That is it, thanks a bunch. Once I realised the error of my ways it all became clear aas day light. Thank you all for having a look.

The console wasn’t returning an error, simply returning an empty object. Thanks for having a look :slight_smile: