this.verifyUserToken块内的代码未执行 。我想它与异步调用有关,因为返回的数据还没有准备好,但我似乎不知道如何去做。
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");
}
};
答案 0 :(得分:0)
由于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");
}
})
};