函数返回不会等待angularjs的承诺

Function return doesn't wait for angularjs promises

本文关键字:angularjs 承诺 等待 返回 函数      更新时间:2023-09-26

我对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. scopeddata .customer. checkforduplicateidentity()方法,并承诺让异步调用工作。

调用工作正常,我测试了它,唯一的问题是我的customerValidation方法在异步调用完成之前完成并一直返回false。也就是说

return isValidated行总是在isValidated变为true之前执行。

我不能让外部返回语句等待异步调用的完成。如果我从内部函数返回isValidated,它不会将值返回给customerValidation函数。有人能告诉我如何做到这一点吗?

调用async函数的函数本身必须是async函数。修改window.customerValidation,使其返回一个promise。

  • 移除var isValidated = false;
  • 第7行用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);

这将在调用函数之前等待50ms。这样你就可以等待异步调用完成。