In real business, it is often necessary to wait for several requests to complete before proceeding to the next step. However, synchronous requests are not supported in Angularjs $http.
Workaround One:
$http. Get (' Url1 '). Success (function (d1) { $http. Get (' Url2 '). Success (function ( D2) { // processing logic } );
Workaround Two:
Then the methods are executed sequentially.
varApp = Angular.module (' app ', []); App.controller (' Promisecontrol ',function($scope, $q, $http) {functionGetjson (URL) {varDeferred =$q. Defer (); $http. Get (URL). Success (function(d) {d=parseint (d); Console.log (d); Deferred.resolve (d); }); returndeferred.promise; } Getjson (' Json1.txt '). Then (function(){ returnGetjson (' Json2.txt '); }). Then (function(){ returnGetjson (' Json1.txt '); }). Then (function(){ returnGetjson (' Json2.txt '); }). Then (function(d) {Console.log (' End '); });});
Workaround Three:
$q. All method The first argument can be an array (object). The then method is executed when the contents of the first parameter are executed. All return values for the method of the first parameter are passed in as an array (object).
var app = Angular.module (' app ', []); App.controller (' promisecontrol ',function($scope , $q, $http) { $q. All ({first: $http. Get (' Json1.txt '), second: $http. Get (' Json2.txt ')}). Then (function (arr) { console.log (arr); Angular.foreach (arr,function(d) { console.log (d); Console.log (d.data); });});
There are many tutorials on how to use $q in detail online. I was just in touch. Don't speak well, dare not talk. The above code is written in my understanding, after the test no problem.
Angularjs $q, $http handle multiple asynchronous requests