ksa_coder
ksa_coder

Reputation: 1403

Ionic + Javascript: How to create promise with Firebase

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:

Upvotes: 0

Views: 33

Answers (1)

CRice
CRice

Reputation: 32146

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");
        }
    });
}

Upvotes: 1

Related Questions