2016-09-14 30 views
0

名前とURLを持つ都市の配列を持っています。Angular Js Promisesを使用して複数の非同期リクエストを作成する

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

今、私は都市のURLにリクエストをする必要があります.1つのリクエストの応答として次々と到着します。

これは約束を使って可能です。 しかし、私は正確な解決策を得ることができません。

答えて

1

あなたは、この例のように再帰ループを使用することができます

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の質問にURLを変更しました。

+0

リクエストは互いに依存しているようには見えないので、同時にリクエストするのがはるかに簡単です – charlietfl

+0

はい、質問は異なるので、独立しているとは確信できません。 –

2

あなたは約束の配列の後にコードを実行するために$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つのリクエストの応答が次々と到着すると、次々と」という質問がありました。これはこれに対する答えではありません。 –

+1

@MaciejSikoraはうまくいっていますが、それは問題のXYの問題ではないと確信していません – charlietfl

+0

タイトルは複数の場合、複数の場合、$ q.all()を使用しています...おそらく、または類似の単語。 –

1

他の回答は複雑です。ここには簡単なものがあります:

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*/)) 
} 

約束事はループ内にあります。

関連する問題