$http 循环,等待结果

$http in loop, wait the results

我有这个:

var j = 0;

// myList.length = 3
while(j < self.myList.length - 1){

    $http.post('myURL', self.myList[j].code).then(
            function(response){

                self.myList[j].plop = response.data;

            }, function(){

                // error

            }
        ).then(
            function(){
                // with this j++, my web page is freezing
                // j++;
            }
        );

    // with this j++, only the 3rd element of myList have a "plop" element
    //j++;
}

我的问题在 "j++" 的评论 :) 中。 如果我删除循环并硬编码第 3 步,它就可以工作。但我不知道如何用循环解决问题。你有好主意吗 ?谢谢

问题是

  1. $http.post().then(function(){}, function(){}) 是异步函数。所以 .then() 方法将在循环完成时执行。这就是它总是取 j 的最后一个值为 2 的原因。
  2. then()$http.post() 只会出现一次,所以删除第二个 .then()

解决方案如下:

var j = 0;
var i = 0;

// myList.length = 3
while(j < self.myList.length - 1){
    $http.post('myURL', self.myList[j].code).then(function(response){
                self.myList[i].plop = response.data;
                i++;

            }, function(){
                // error
            }
        );
}

根据OP评论的同步解决方案:

var promises = [];
for(var i=0;i<self.myList.length;i++)
 promises.push($http.post(...));
$q.all(promises).then(function(results){
 //All results available here
 var data = results.map(result => result.data);
 data.forEach((e, idx) => self.myList[idx] = e);
})
.catch(function(e){
 //Handle error
});