Angularjs $q, $http handle multiple asynchronous requests
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.
var app = Angular.module (' app ', []); App.controller (' Promisecontrol ', function ($scope, $q, $http) { function Getjson (URL) { var deferred = $q. Defer (); $http. Get (URL) . Success (function (d) { d = parseint (d); Console.log (d); Deferred.resolve (d); }); return deferred.promise; } Getjson (' Json1.txt '). Then (function () { return Getjson (' Json2.txt '); }). Then (function () { return Getjson (' Json1.txt '); }). Then (function () { return Getjson (' 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);});}) ;
Workaround Four:
var app = Angular.module (' app ', []); App.controller (' Directivecontrol ', function ($scope, $http, $q) { function Gettxt (a) { var deferred = $q. Defer (); $http. Get (' 1.json ') . Success (function (d) { console.log (a); Deferred.resolve (); }) return deferred.promise; } Gettxt (1). Then (function () { return gettxt (2); }). Then (function () { return gettxt (3); }). Then (function () { return gettxt (4); }). Then (function () { return gettxt (5); }). Then (function () { console.log (' End '); });
There are many tutorials on how to use $q in detail online. I was just in touch. The above code is written in my understanding, after the test no problem.
Angularjs $q, $http handle multiple asynchronous requests