Reputation: 1978
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.
Upvotes: 1
Views: 991
Reputation: 2543
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");
}
});
Upvotes: 2
Reputation: 317712
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.
Upvotes: 3