由于js脚本语言的独特性,当同时调用多个接口时就不得不处理js的异步问题。在AngularJs中解决异步的方法之一:使用$q的defer方法,defer方法会返回一个对象,我们常调用resolve()和reject()处理成功时的响应数据和失败时的响应数据,接下来在方法中返回一个primose对象,最终调用方法,使用.then()处理成功回调函数和失败回调函数。 接下来我将以举例的形式详细解析上述一段话, 具体阐释可以看代码的注释部分。
- AngularJs项目中注入$q服务。
**app.controller('IndexSideCtrl', function (DialogService, $scope, $state, $http, $rootScope, $q, $sce, $timeout, blockUi,translateService) {
})**
- 在控制器中使用$q服务
app.controller('indexCtrl', function (DialogService, $scope, $state, $http, $rootScope, $q, $sce, $timeout, blockUi,translateService) {//注入$q
$scope.deferredObj = $q.defer();//调用defer方法
$scope.getData = function () {
$http.get(url).success(function(data){
$scope.deferredObj.resolve(data);//处理成功时候的返回数据
}).error(function(data){
$scope.deferredObj.resolve(data);//处理失败时候的返回数据
});
return $scope.deferredObj.promise;//promise是一种对执行结果不确定的一种预先定义,也就是说有可能成功也有可能失败,这个就是一个预先定义的一个结果。
};
$scope.getData ().then(function(data) {//该data即为$scope.getData方法返回的promise
$scope.getOtherData(data);//此时就可以在getOtherData方法中使用data
});
})
- .then()的链式调用可以处理多个接口的异步问题。比如说我们需要先调用方法A(方法A里面有接口)获取数据a, 在方法B中(B方法里面也有一个接口)使用a数据获取数据b, 在方法C中使用方法B获取的数据b。
getA().then(function(a) {
return getB(a)
}).then(function(b) {
return getC(b)
}).then(function(success){
console.log(success);
},function(err){
console.log(err);
});