首页 > 解决方案 > $http 获取循环将响应数据附加在一起

问题描述

我有一个链接列表,每个链接都有一个数字,从 1 到有多少。我的目标是编写一个 for 循环,它遍历每个链接,运行 HTTP get,然后将响应数据保存到数组对象中。我尝试了各种方法,但由于我正在处理 $scope 变量这一事实,这很困难,所以我发现没有一种方法有效。

for (let i = 0; i < 1000; i++) {
  $http.get("Start of URL"
+ i +  "End of URL")
  .then(function (response){
    $scope.datasingle = response.data;
  }); 
  $scope.datacombined = ??  

}

标签: javascriptarraysangularjs

解决方案


试试这个方法;

const promisses = [];
for (let i = 0; i < 1000; i++) {
  promisses.push( new Promise(function (resolve, reject) {
    $http.get("Start of URL"+ i +  "End of URL").then(function(response){
      resolve(response.Data);
    });
  }));
}

Promise.all(promisses).then(function (values) {
  console.log(values); //you will get all the resolved result in this array and do what you want
});

推荐阅读