In actual business, you often need to wait for several requests to complete before proceeding with the next step. But $http in angularjs does not support synchronous requests.
Solution 1:
The code copy is as follows:
$http.get('url1').success(function (d1) {
$http.get('url2').success(function (d2) {
//Processing logic
});
});
Solution 2:
The methods in then will be executed in order.
The code copy is as follows:
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');
});
});
Solution three:
The first parameter of the $q.all method can be an array (object). After all the contents in the first parameter are executed, the method in then will be executed. All return values of the method of the first parameter are passed in as an array (object).
The code copy is as follows:
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 the detailed usage of $q. I'm just getting in touch too. If you can't speak well, you dare not talk nonsense. The above code was written according to my understanding, and there was no problem after testing.