在實際業務中常常須要等待幾個請求完成後再進行下一步操做。但angularjs中$http不支持同步的請求。
解決方法一:angularjs
$http多層嵌套
$http.get('url1').success(function (d1) { $http.get('url2').success(function (d2) { //處理邏輯 }); });
解決方法二:
then中的方法會按順序執行。json
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'); }); });
解決方法三:
$q.all方法第一個參數能夠是數組(對象)。在第一參數中內容都執行完後就會執行then中方法。第一個參數的方法的全部返回值會以數組(對象)的形式傳入。數組
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); }) }); });