For循环没有正确执行http服务

时间:2017-01-10 21:10:39

标签: javascript angularjs

我试图通过函数(callAPI)在for循环中调用http服务。 这是我的代码。我使用此代码时遇到的问题是,当http服务赶上时,我没有按照正确的顺序获取正确的ID。在callAPI函数上,它甚至在运行一个http服务异步请求之前经过了console.log(id)的所有调用,然后它运行了http服务调用但是id的顺序错误。例如,我回来了一个[6,6,3]的数组,它按[3,6,6]的顺序运行。任何帮助表示赞赏。

for (var i = 0; i < idArray.length; i++) {
    callAPI(idArray[i]);
}

function getItems() {
    return self.choices;
}

function callAPI(id) {
    console.log(id);

$http({
    method: 'GET',
    url: '/api/organizations/' + orgID + '/' + id + '/meal'
}).success(function (data) {
    console.log(id);
    console.log(data);
    // idLocal = id;
    angular.forEach(data, function(value,key) {
        angular.forEach(value, function(value,key) {
            angular.forEach(value, function(value,key) {

                if (key == 'description') {
                    items.push(value);
                }

                if (key == 'drop_name') {
                    self.dropName = value;
                }
            });
        });
    });

    self.choices.push({
        id: id,
        choice: items,
        dropname: self.dropName
    });

    items = [];

    getItems();

}).error(function (data) {
    console.log('failed');
});
}

1 个答案:

答案 0 :(得分:2)

我更喜欢这样做,但还有其他多种解决方案:

//set index
var index = 0;
function callAPI(id) {
    //increment index
    index++
    $http({
        method: 'GET',
        url: '/api/organizations/' + orgID + '/' + id + '/meal'
    }).success(function (data) {
        //call function again with next index if exists
        if (index <= idArray.length) {
            callAPI(idArray[index])
        }

    }).error(function (data) {
        console.log('failed');
    });
}
//call function with 0 index
callApi(idArray[index])

这将运行一个异步请求,当返回时,然后运行下一个。您当然可以以任何方式处理返回数据。另外,正如使用angular&#34; q&#34;中包含的promise库所提到的那样。是另一个不错的选择。