[英]Function return doesn't wait for angularjs promises
我對angularjs的承諾有疑問,也許有人可以指出我正確的方向。 我的控制器中有一個驗證函數,如果一切正常,則應返回true,如果有問題,則應返回false。 單頁應用程序可在此假設下工作,因此我無法輕松更改此假設...
window.customerValidation = function ($scope, $rootScope, $alert, $q) {
var isValidated = false;
if (!$scope.scopeData.customer.nationalId && !$scope.scopeData.customer.passportNumber && !$scope.scopeData.customer.driverLicenseNumber) {
$alert.error("Please enter at least one identification info.");
return false;
}
$scope.scopeData.customer.checkForDuplicateIdentity().then(function () {
var customer = $scope.scopeData.customer;
if (!customer.idValidated) {
$alert.error(customer.idValidationMessage);
}
if (!customer.idValidated)
{
return false;
}
if ($scope.customerDataForm && $scope.customerDataForm.$error && $scope.customerDataForm.$error.required) {
var missingFields = [];
angular.forEach($scope.customerDataForm.$error.required, function (value, key) {
missingFields.push("-" + value.$name);
});
$alert.error("Please fill in the all required fields.\r\n" + missingFields.join("\r\n"));
}
else if ($scope.customerDataForm && $scope.customerDataForm.$error && $scope.customerDataForm.$error.email) {
var invalidEmailFields = [];
angular.forEach($scope.customerDataForm.$error.email, function (value, key) {
invalidEmailFields.push("-" + value.$name);
});
$alert.error("Please enter valid e-mail addresses.\r\n" + invalidEmailFields.join("\r\n"));
}
else if (!Date.parse($scope.scopeData.customer.dateOfBirth)) {
$alert.error("Please enter a valid date for Date of Birth.");
}
else {
$scope.scopeData.customer.updateIndividualCustomerInfoRequest();
$scope.scopeData.customer.updateOrder();
$rootScope.customerName = $scope.scopeData.customer.firstName + " " + $scope.scopeData.customer.lastName;
isValidated = true;
}
});
return isValidated;
};
在需求最近改變之前,一切工作正常,我試圖檢查服務器以查看以前是否在系統中使用過id值。 因此,我必須對服務器進行異步調用並對其進行檢查,您可以看到我使用了$ scope.scopeData.customer.checkForDuplicateIdentity()方法,並承諾將進行異步調用。
調用工作正常,我對此進行了測試,唯一的問題是我的customerValidation方法在異步調用完成之前始終完成,並且始終返回false。 那是說
返回isValidated行始終在isValidated變為true之前執行。
我不能讓外部return語句等待異步調用的完成。 如果我從內部函數返回isValidated,則不會將值返回給customerValidation函數。 有人可以告訴我如何實現嗎?
調用異步函數的函數本身必須是異步函數。 更改window.customerValidation
以便它返回承諾。
var isValidated = false;
return $q.reject()
代替return false
$scope.scopeData.customer.checkForDuplicateIdentity()
前面添加返回 then
的回調中,驗證通過后return
,驗證失敗則throw
錯誤 然后在window.customerValidation
的調用者中替換
if (window.customerValidation()) {
// validation passed
} else {
// validation failed
}
通過
window.customerValidation()
.then(function () {
// validation passed
})
.catch(function (error) {
// validation failed
})
您可以隨時使用javascript提供的超時功能,例如
setTimeout(function {DO_SOMETHING}, 50);
這將等待50毫秒,然后再調用該函數。 這樣,您可以等待異步調用完成。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.