AngularJS + $ q, do something after completing multiple ajax calls

I need to upload some data to load the page, and then complete the task. to get the data i want, i make a few different ajax calls. But to complete the task, I need everything to make sure that all ajax calls are complete. Here is what I have done so far:

$q.when( $http.get('url1').success(function (data) { $scope.data1 = data; console.log("ajax1 finished"); }), $http.get('url2').success(function (data) { $scope.data2 = data; console.log("ajax2 finished"); }), $http.get('url3').success(function (data) { $scope.data3 = data; console.log("ajax3 finished"); }), $http.get('url4').success(function (data) { $scope.data4 = data; console.log("ajax4 finished"); }) ).then( console.log("All ajax calls have finished!"), executeTask() ); 

My problem is that the code in the then(...); block then(...); not executed after ajax call ends. I get something like this in my console:

 ajax2 finished ajax1 finished All ajax calls have finished! ajax3 finished ajax4 finished 

I have to do something wrong. How can I make it work the way I want?


Change I tried the following, as mentioned in the answers, but I am still facing the same problem.

 $q.all([ $http.get('url1').then(function (data) { $scope.data1 = data; console.log(""); }), $http.get('url2').success(function (data) { $scope.data2 = then; console.log("ajax2 finished"); }), $http.get('url3').then(function (data) { $scope.data3 = data; console.log("ajax3 finished"); }), $http.get('url4').then(function (data) { $scope.data4 = data; console.log("ajax4 finished"); }) ]).then( console.log(""), executeTask() ); 
+7
javascript angularjs ajax angular-promise
source share
2 answers

I made a working plunk for you using $q.all()

http://plnkr.co/edit/JHd3XPTKBxx4KRso5JRB?p=preview

  $q.all([ $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) { $scope.ip.one = response.data console.log('one') }), $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) { $scope.ip.two = response.data console.log('two') }), $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) { $scope.ip.three = response.data console.log('three') }), $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) { $scope.ip.four = response.data console.log('four') }), ]).then(function() { console.log('all') }) 
+13
source share

You have two solutions:

+2
source share

All Articles