0

Before you say "The variable must be declared globally, and not inside the function", it already is .

In a Node/Express setup I retrieve the value of a the variable loggedIn from the BE. This is 1 if the user is logged in, and 0 if the user is not. The value should determine which header is loaded.

This is the code, let's say user A is logged in:

    let loggedIn = 0 // VALUE IS DECLARED OUTSIDE THE FUNCTION LIKE IT SHOULD BE

    async function checkLoggedIn () { // THE FUNCTION TO CHECK IS USER IS LOGGED IN
        const res = await fetch('users/authenticate')
        const loggedInString = await res.json()
        loggedIn = parseInt(loggedInString)
        console.log(loggedIn) // THIS LOGS OUT '1' LIKE IT SHOULD BECAUSE USER A IS LOGGED IN
    }

    checkLoggedIn() // WE RUN THE FUNCTION

    console.log(loggedIn) // THIS LOGS OUT '0' EVEN THOUGH USER A IS LOGGED IN

For the life of me, I can't figure out why the value of loggedIn is 0 outside the function.

One thing to note is that the log first logs out the value of loggedIn outside the function (i.e. the second instance in the code). Why is that? The function is being called before the console.log(loggedIn) outside the function is run.

This is what the browser logs out when the code is run:

0 (index):12 // VALUE OUTSIDE THE FUNCTION
1 (index):7 // VALUE INSIDE THE FUNCTION

Line 12 is logged out before line 7, which I don't understand.

I am sure there is a simple explanation, but I just don't get it.

Vemb
  • 109
  • 2
  • 7
  • 2
    `checkLoggedIn()` is async, so your `loggedIn = 1` assignment hasn't run by the time it hits the 2nd `console.log()`. You'll need to `await` the `checkLoggedIn()` call, or chain a `.then` to run some code afterward. e.g. `await checkLoggedIn(); console.log(loggedIn) // 1` or `checkLoggedIn().then(() => { console.log(loggedIn) }); – romellem Aug 31 '22 at 16:18
  • @romellem, Thanks! I (wrongly) assumed that the `await` inside the function would halt the execution of the code until a response was received and stored. I'll need to study this a bit more. – Vemb Aug 31 '22 at 16:49

0 Answers0