我有一個城市數組,其名稱和URL。使用Angular Js Promises製作多個異步請求
$scope.cities = [{'name':'LKO','url': 'http://sm.com'},{'name':'LK1O','url': 'http://sm1.com'}]
現在我需要對城市中存在的URL發出請求..一個接一個的請求作爲一個請求的響應到達。
我知道這是可能使用的承諾。 但是,我無法得到確切的解決方案。
我有一個城市數組,其名稱和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問題的網址。
可以使用$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
投入使用或控制器,你提出這些要求
問題是「隨着一個請求的響應到來,一個接一個」。這不是一個答案。 –
@MaciejSikora很好,但我不知道是不是有問題 – charlietfl
)的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*/))
}
你只是鏈接在一個循環的承諾。
更快做出的併發請求,雖然因爲請求不會出現依賴於彼此 – charlietfl
是的,但問題是不同的,所以你不能肯定他們是獨立的。 –