Ionic + Javascript:如何使用Firebase创建承诺

时间:2018-02-14 23:52:31

标签: javascript firebase ionic-framework firebase-realtime-database ionic3

我有doRegisterUser()的简单功能,它基本上使用提供程序中定义的函数来检查用户名是否已经注册。在下面的代码中,我打印到控制台,调用提供程序的功能,然后打印到控制台。我只是为了观察执行顺序而这样做。我想要的是checkUsernameReserved()执行然后任何控制台打印发生。

如何实现这一目标?

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

这是使用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");
      }
    })
  }

我在控制台中获得的当前输出是:

  • 在checkUsernameReserved()执行
  • 之前
  • checkUsernameReserved()执行后
  • 用户名

1 个答案:

答案 0 :(得分:1)

两件事:

  • checkUsernameReserved
  • 返回您的承诺
  • 将检查后必须运行的代码放入该承诺的.then

所以:

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