【问题标题】:$http in loop, wait the results$http 在循环中,等待结果
【发布时间】:2016-06-22 15:56:15
【问题描述】:

我有这个:

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++”的 cmets :)。 如果我删除循环并硬编码第 3 步,它就可以工作。但我不知道如何用循环解决这个问题。你有想法吗 ?谢谢

【问题讨论】:

    标签: angularjs synchronization promise http-post


    【解决方案1】:

    根据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
    });
    

    【讨论】:

      【解决方案2】:

      问题是

      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
                  }
              );
      }
      

      【讨论】:

      • 谢谢,它效果更好,但并不完全。实际上,$post 是并行执行的。所以,var "i" 是不同步的。
      猜你喜欢
      • 2020-10-21
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2018-05-25
      • 1970-01-01
      • 2021-11-20
      • 2022-01-16
      相关资源
      最近更新 更多