atulquest93 atulquest93 - 2 months ago 11
AngularJS Question

Make multiple Async Request using Angular Js Promises

I have an array of cities with their name and url .

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


Now I need to make request to the url present in the city.. One after another as response of one request arrives.

I know this is possible using promises.
But, I'm not able to get the exact solution.

Answer

You can use recursive loop like in this example:

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. i changed url to this github question.

Comments