1

I am trying to check if a user is logged in and return true or false based on that. But the function return before the firebase call is completed.

async function checkLogin() {
    var result;

    await firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
          result = true;
          console.log("user is signed in");
        } else {
        result = false;
          console.log("user is not signed in");
        }
        });
        console.log("End of function");
        return result;
}

"End of function" gets printed out before any of the above two. The value in result is always undefined. It seems the function returns before the completion of firebase.auth(). Is there a way I can make it wait before returning.

GunJack
  • 1,928
  • 2
  • 22
  • 35

2 Answers2

3

onAuthStateChanged() does not return a promise, it returns an unsubscribe function. You use onAuthStateChanged() to add a listener/observer/subscriber that get invoked as the sign-in state changes over time. You can write code inside that callback to do what you want as the user become signed in or out. Promises won't help you here - design your code to use that callback instead.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
2

As Doug mentioned, onAuthStateChanged() does not return a promise but an event, you can rather change your logic to:

async function afterLoginTask() {
    var result;
    // perform UI or other changes
    return result;
}

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      console.log("user is signed in");
      afterLoginTask()
    } else {
      console.log("user is not signed in");
    }
});
frunkad
  • 2,433
  • 1
  • 23
  • 35