使用Angular Js Promises制作多个异步请求

问题描述:

我有一个城市数组,其名称和URL。使用Angular Js Promises制作多个异步请求

$scope.cities = [{'name':'LKO','url': 'http://sm.com'},{'name':'LK1O','url': 'http://sm1.com'}] 

现在我需要对城市中存在的URL发出请求..一个接一个的请求作为一个请求的响应到达。

我知道这是可能使用的承诺。 但是,我无法得到确切的解决方案。

您可以在这个例子中使用递归循环,如:

var app=angular.module("app",[]); 
 

 
app.controller("main",function($scope,$q,$http){ 
 

 
    
 
$scope.cities = [{'name':'LKO','url': 'http://stackoverflow.com/posts/39497624'},{'name':'LK1O','url': 'http://stackoverflow.com/posts/39497624'}, 
 
{'name':'LK21','url': 'http://stackoverflow.com/posts/39497624'}] 
 
    
 
    //recursive function 
 
    function getUrl(i){ 
 
     
 
     if (typeof $scope.cities[i]=='undefined') 
 
     return; //last one 
 
     
 
     console.log("ajax to "+ $scope.cities[i].url); 
 
     $http.get($scope.cities[i].url).then(getUrl(i+1)); 
 
    }; 
 
    
 
    getUrl(0);//start 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="main"> 
 
</div>

PS。我改变了这个github问题的网址。

+0

更快做出的并发请求,虽然因为请求不会出现依赖于彼此 – charlietfl

+0

是的,但问题是不同的,所以你不能肯定他们是独立的。 –

可以使用$q.all()承诺数组后运行的代码都解决

var promises = $scope.cites.map(function(city) { 
    return $http.get(city.url).then(function(resp) { 
    var cityData = resp.data; 
    // do something with cityData here 

    // then return it 
    return cityData; 
    }); 
}); 

$q.all(promises, function(cityDataArray) { 
    // do something with array 
}); 

这种方法假定请求是不依赖于对方,是不是做递归

快得多确保注入$q投入使用或控制器,你提出这些要求

+0

问题是“随着一个请求的响应到来,一个接一个”。这不是一个答案。 –

+1

@MaciejSikora很好,但我不知道是不是有问题 – charlietfl

+0

)的XY问题,题曰“多” ......多,它的使用$ q.all(...可能是一个更好的标题是“顺序“或类似的词。 –

其他的答案是复杂的。这里是一个更简单的:

const cities = [{'name':'LKO','url': 'http://sm.com'}, ...] 
const queue = $q.resolve(); // get an empty promise 
for(const city of cities) { // angular.forEach if you want to avoid for...of 
    queue = queue.then(() => $http.get(city.url).then(/* write result to scope*/)) 
} 

你只是链接在一个循环的承诺。