angularJS中的promise

promise对象解析

var ngApp = angular.module('ngApp', []);
// $q为内置服务
ngApp.factory('UserInfoService', ['http','$q', function($http, $q) {
    return {
        query: function() {
            var defer = $q.defer(); //声明延后执行
            $http({method: 'GET', url: 'data/students.json'})
                .success(function(data, status, headers,config) {
                    defer.resolve(data); //声明执行成功
                    console.log('UserInfoService success');
                })
                .error(function(data, status, headers, config) {
                    defer.reject(); // 声明执行失败
                });
                return defer.promise; //返回承诺,返回获取数据的API 
        }
    }
}]);

ngApp.contrtoller('MainController', ['$scope','UserInfoService', function($scope, UserInfoService) {
    var promise = UserInfoService.query(); //同步调用,获取承诺接口
    promise.then(function(data) {
        $scope.user = data; //调用承诺接口resolve()
        console.log('MainController..');
    }).catch(function(data) {
        $scope.user = {error: '数据不存在'}; //调用承诺接口reject()
    })
}])
  1. promise是一种由的方式处理值的方法,是对象,表明了一个函数最终可能的返回值或者抛出的异常。编程

  2. promise可使用链式编程json

好比:promise

Service.then(function(data) {

    // 在这里必定要用 return 返回
}).then(functon(data) {
    
}).catch(function(data){

})
相关文章
相关标签/搜索