gpt4 book ai didi

javascript - ionic + JavaScript : How to create promise with Firebase

转载 作者:行者123 更新时间:2023-12-03 02:29:29 26 4
gpt4 key购买 nike

我有 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() 后
  • 用户名已被占用

最佳答案

有两件事:

  • 返回 checkUsernameReserved 的 promise
  • 将必须在检查后运行的代码放入该 Promise 的 .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");
}
});
}

关于javascript - ionic + JavaScript : How to create promise with Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48798109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com