Как дождаться обещания, чтобы завершить с возвращенным значением, используя angularjs - PullRequest
0 голосов
/ 05 октября 2018

У меня проблема с моим проектом.В моем контроллере 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, подождитедля его завершения, а затем вернуть заполненный массив?После того, как заполненный массив будет возвращен (result), выполните функцию updateArchivedImportFlag.

Ниже я добавил иллюстрацию того, чего я хотел бы достичь:

For loop logic

1 Ответ

0 голосов
/ 05 октября 2018

Я использую подход, сохранив все обещания в массиве.Используйте любую библиотеку обещаний или es6 Promise и используйте функцию .all для ожидания выполнения всех обещаний

Синтаксис, который я написал, не совсем корректен.Поскольку вы используете угловой 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
        })
    };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...