-->

Random sequence of response in $http.get

2019-07-14 15:39发布

问题:

I'm trying to write a function that sends multiple requests to the server based on the number of Ids in the idArray. The problem I'm facing is that the data that is pushed into the dataArray does not follow the proper sequence of the corresponding Ids of the idArray. I tried adding the timeout to the HTTP requests so that the previous request is fully processed before the next iteration of the for loop, but that too does not seem to work. Please help.

function commonService($http, $q) {
    return {
        getAboutContent: function() {
            var dataArray = [];
            var deferred = $q.defer();
            var idArray = ['about2', 'about3'];
            var count = 0;
            angular.forEach(idArray, function(id) {
                $http.get('server url/' + id).success(function(data) {
                    dataArray.push(data);
                    count++;
                    if (count == idArray.length) {
                        deferred.resolve(dataArray);
                    }
                }).error(function(error) {
                    console.log('error', error);
                    deferred.reject(error);
                });
            });
            return deferred.promise;
        }
    }
}

回答1:

You can not say with surety that the first AJAX call will be completed first as that is the asynchronous call. So if you are doing 3 calls using your for loop you can not guarantee that the response will come in the same order. So, assuming you can return the id from the server AJAX call then you can write like this:

function commonService($http, $q) {
    return {
        getAboutContent: function() {
            var dataArray = [];
            var deferred = $q.defer();
            var idArray = ['about2', 'about3'];
            var count = 0;
            angular.forEach(idArray, function(id) {
                $http.get('server url/' + id).success(function(data) {
                    // Return the "id" from the response and get the index position in the "idArray"
                    var idIndex = idArray.indexOf(data.id);
                    // Then insert data into the specific index as of "id"
                    dataArray[idIndex] = data;

                    count++;
                    if (count == idArray.length) {
                        deferred.resolve(dataArray);
                    }
                }).error(function(error) {
                    console.log('error', error);
                    deferred.reject(error);
                });
            });
            return deferred.promise;
        }
    }
}