0

I have the simple function of doRegisterUser() which basically uses a function defined in a provider to check if username already registered or not. In the following code, I print to console, call provider's function and then print to console. Simply I am doing this just to observe the sequence of execution. What I want is to have checkUsernameReserved() execute and then any the console print to happen.

How can this be accomplished?

doRegisterUser() {
        var self = this;
        /*Step A - Check username provided by user is taken or not. If no username taken, create random username*/
        console.log("Before checkUsernameReserved() execution");



        self.firebaseProvider.checkUsernameReserved(self.username);



        console.log("After checkUsernameReserved() execution");
    }

and this is the provider function which uses the firebase:

checkUsernameReserved(username:string): any{
    /*Check usernamesTaken table for provided username*/
    firebase.database().ref('/usernames_taken/' + username).once('value').then(function(snapshot) {

      /*Check if username is taken.*/
      if(snapshot.val() != null && snapshot.val() != "")
      {
        console.log("Username Taken");
      }else{
        console.log("Username Available");
      }
    })
  }

The current output I am getting in console is:

  • Before checkUsernameReserved() execution
  • After checkUsernameReserved() execution
  • Username Taken

1 Answer 1

1

Two things:

  • Return your promise from checkUsernameReserved
  • Put code that must run after the check in the .then of that promise.

So:

doRegisterUser() {
    var self = this;
    /*Step A - Check username provided by user is taken or not. If no username taken, create random username*/
    console.log("Before checkUsernameReserved() execution");
    self.firebaseProvider.checkUsernameReserved(self.username).then(() => {
        // Put code that must run after the check in here...
        console.log("After checkUsernameReserved() execution");
    }); 
}

checkUsernameReserved(username:string): any{
    /*Check usernamesTaken table for provided username*/
    // !! note the return !!
    return firebase.database().ref('/usernames_taken/' + username).once('value').then(function(snapshot) {

        /*Check if username is taken.*/
        if(snapshot.val() != null && snapshot.val() != "") {
            console.log("Username Taken");
        } else {
            console.log("Username Available");
        }
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! that worked smoothly. I will make sure to read more to fully understand my options in such a scenario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.