gpt4 book ai didi

javascript - ref 内的代码一旦不执行 angularjs

转载 作者:行者123 更新时间:2023-11-28 05:49:36 25 4
gpt4 key购买 nike

this.verifyUserToken block 内的代码不会执行。我猜这与异步调用有关,因为返回的数据尚未准备好,但我似乎不知道如何处理。

this.verifyUserToken = function(){
//Check if token matches existing token and if verified is true
ref.orderByChild('token').equalTo(this.token).once('value').
then(function(dataSnapshot){
//If token matches
if(dataSnapshot.val()){
alert("Token Exists",dataSnapshot.val().token);
$scope.isVerified = "YES";
}else{
alert("Token does not exist",dataSnapshot.val());
$scope.isVerified = "NO";
}
});
}

this.registerUser = function(){
console.log("Entered registerUser()");

this.verifyUserToken();
alert("The Value of isVerified:"+ $scope.isVerified);
if($scope.isVerified == "YES"){
alert("Verifying User Token...",this.verifyUserToken());
$scope.auth.$createUser({
"email": this.email,
"password" : this.password
}).then(function(userData){
alert("Successfully created user account with uid:", userData.uid);
//redirect to /userlogin if registration is successful
//this.changeVerifiedStatus();
alert("User verifed and changed");
$location.path('/userlogin');
}).catch(function(error){
alert("Error Creating User:",error);
});
}else{
alert("Token failed verification");
}
};

最佳答案

由于 verifyUserToken 有一个对 firebase 的异步调用,您可以处理它从该函数返回 Promise ,并仅在完成后继续您的 registerUser然后验证通话已完成。

我设置了 jsFiddle这样你就可以看到它的工作原理。

this.verifyUserToken = function(){
//Check if token matches existing token and if verified is true
var verifyUserTokenPromise = new Promise(function(resolve, reject){
ref.orderByChild('token').equalTo(this.token).once('value').then(function(dataSnapshot){
//If token matches
if(dataSnapshot.val()){
alert("Token Exists",dataSnapshot.val().token);
$scope.isVerified = "YES";
}else{
alert("Token does not exist",dataSnapshot.val());
$scope.isVerified = "NO";
}
//resolve the promise. you can pass any data here
resolve($scope.isVerified);
});
});
return verifyUserTokenPromise;
};

this.registerUser = function(){
console.log("Entered registerUser()");

this.verifyUserToken().then(function(result){
alert("The Value of isVerified:"+ $scope.isVerified);
if($scope.isVerified == "YES"){
alert("Verifying User Token...",this.verifyUserToken());
$scope.auth.$createUser({
"email": this.email,
"password" : this.password
}).then(function(userData){
alert("Successfully created user account with uid:", userData.uid);
//redirect to /userlogin if registration is successful
//this.changeVerifiedStatus();
alert("User verifed and changed");
$location.path('/userlogin');
}).catch(function(error){
alert("Error Creating User:",error);
});
}else{
alert("Token failed verification");
}
})
};

关于javascript - ref 内的代码一旦不执行 angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38187035/

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