代码之家  ›  专栏  ›  技术社区  ›  slee423

如何使用angularjs等待promise完成返回值

  •  1
  • slee423  · 技术社区  · 6 年前

    我对我的项目有意见。在我的angularjs控制器中,一个函数正在执行,然后我调用数据库来更新记录的函数正在执行,而不等待第一个函数完成,因此发送一个未定义的 result

    在下面,您可以找到我的代码片段和我迄今为止的尝试。

    提交按钮功能:

    $scope.submitNewStarters = function () {
    
        // result is returning as undefined <<<<< Issue
        var result = $scope.sendNewStarterDetailsToApi();
    
        $scope.updateArchivedImportFlag(result); 
    
    };
    

    $scope.sendNewStarterDetailsToApi = function () {
    
    swal({
        title: "Confirmation",
        text: "Are you sure you want to import the new starter details?",
        icon: "info",
        dangerMode: true,
        buttons: ["No", "Yes"]
    }).then(function (approve) {
    
        if (approve) {
    
            // Get each of the new starter details that have been set to true for import.
            var newStartsToImport = $scope.tableParams.data.filter(x => x.imported == true);
    
            for (let i = 0; i < newStartsToImport.length; i++) {
    
                // Parses the current new starter object into a stringified object to be sent to the api.
                $scope.newStartsToImport = $scope.createApiObject(newStartsToImport[i]);
    
                // A check to ensure that nothing has went wrong and that the stringify object has worked.
                if ($scope.newStartsToImport !== "") {
    
                    apiFactory.postNewStarterDetailsToApi($scope.newStartsToImport).then(function (response) {
    
                        var isSuccessful = response.data.d.WasSuccessful;
    
                        if (isSuccessful)
                            toastr.success("New starter details successfully sent to API.", "Success!");
                        else {
                            var errorMessage = response.data.d.ErrorMessage;
                            toastr.error("New starter details were unsuccessfully sent to API. Please try again. \n" + errorMessage, "Error!");
                        }
    
                    });
                }
                else {
                    toastr("An error has occurred when attempting to create the data object to be sent to API. The process has stopped!", "Error!");
                    break;
                }
            }
    
            return newStartsToImport;
        }
        else
            toastr.info("No new starter details were sent to API", "Information!");
        });
    };
    

    API调用的工厂函数:

    postNewStarterDetailsToApi: function (data) {
        return $http({
            url: "https://www.example.com/services/service.svc/Import",
            method: "POST",
            data: data,
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
            }
        }).then(function successCallbwack(response) {
            // this callback will be called asynchronously
            // when the response is available
            return response;
        }, function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            console.log('An error has occured during the function call postNewStarterDetailsToApi(): ', response);
        });
    }    
    

    所以有了承诺的概念,我怎么才能履行承诺呢 sendNewStarterDetailsToApi )返回,然后执行 updateArchivedImportFlag 功能。

    下面我添加了一个我想要达到的目标的例子:

    For loop logic

    1 回复  |  直到 6 年前
        1
  •  1
  •   sridhar..    6 年前

    我使用的方法是,将所有承诺保存在一个数组中。 使用任何promise库或es6 promise,并使用.all函数等待所有承诺执行

    我写的语法不完全正确。因为您使用的是angular js,所以可以使用$q all

    $scope.sendNewStarterDetailsToApi = function () {
    
        swal({
            title: "Confirmation",
            text: "Are you sure you want to import the new starter details?",
            icon: "info",
            dangerMode: true,
            buttons: ["No", "Yes"]
        }).then(function (approve) {
            var res = [];
            if (approve) {
        
                // Get each of the new starter details that have been set to true for import.
                var newStartsToImport = $scope.tableParams.data.filter(x => x.imported == true);
        
                for (let i = 0; i < newStartsToImport.length; i++) {
        
                    // Parses the current new starter object into a stringified object to be sent to the api.
                    $scope.newStartsToImport = $scope.createApiObject(newStartsToImport[i]);
        
                    // A check to ensure that nothing has went wrong and that the stringify object has worked.
                    if ($scope.newStartsToImport !== "") {
                        res.push(apiFactory.postNewStarterDetailsToApi($scope.newStartsToImport))
                    }
                    else {
                        toastr("An error has occurred when attempting to create the data object to be sent to API. The process has stopped!", "Error!");
                        break;
                    }
                }
        
                return Promise.all(res);
            }
            else
                toastr.info("No new starter details were sent to API", "Information!");
            }).then(function (data) {
                data.forEach((response) => {
                    var isSuccessful = response.data.d.WasSuccessful;
    
                    if (isSuccessful)
                        toastr.success("New starter details successfully sent to API.", "Success!");
                    else {
                        var errorMessage = response.data.d.ErrorMessage;
                        toastr.error("New starter details were unsuccessfully sent to API. Please try again. \n" + errorMessage, "Error!");
                    }
                })
            }).then((res) => {
                //call Submit new starters
            })
        };