Sidath Munasinghe
Sidath Munasinghe

Reputation: 359

How to handle the order when executing the callbacks?

I'm using firebase for authentication in my angular2 app and I'm having a issue with callbacks. Here is my code segment to identify whether a user has logged in or not.

verifyLogin(url: string): boolean {
var myUser = null;
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    myUser = user;
    console.log("sdfsdfsd");
    console.log(myUser);
  } else {
    // No user is signed in.
  }
});
console.log("check");
console.log(myUser);
if(myUser){
  return true;
}
console.log(myUser);
this.router.navigate(['/admin/signin']);
return false;

}

This verifyLogin function will return true if user has logged in and false otherwise. But the problem is bottom part which contains the if condition executes before executing the callback. I can't return inside the callback as well. How to fix this?

Upvotes: 0

Views: 65

Answers (1)

samAlvin
samAlvin

Reputation: 1678

One way to solve this is to make verifyLogin() returns a Promise. This way, verifyLogin() will only return either true or false after onAuthStateChanged() finished.

verifyLogin(url: string): Promise<boolean> {
    return new Promise((resolve) => {
        var myUser = null;
        firebase.auth().onAuthStateChanged(function(user) {
            if (user) {
                myUser = user;
                console.log("sdfsdfsd");
                console.log(myUser);
                resolve(true);
            } else {
                // No user is signed in.
                resolve(false);
            }
        });
    });
}

And then you can call the verifyLogin() like this:

verifyLogin("someUrl").then(isLoggedIn => {
    if (isLoggedIn == false) {
        this.router.navigate(['/admin/signin']);
    }
});

Upvotes: 3

Related Questions