理解 AngularJS $q service and promises

Angularjs中的“$q”和 http访问的promises对象经常见到,本文主要介绍 AngularJS $q service and promises。

原文地址 http://haroldrv.com/2015/02/understanding-angularjs-q-service-and-promises/

介绍Angularjs $q service之前,我们需要了解promise是什么,它的作用是什么。

什么是promise

promise在JavaScript和angularjs中,是指我们通过执行某个动作(如:click button)后,在将来某个时间点返回数据的对象。让我们看以下两种情况。
  • promise被填充——通过执行某个动作后,返回的数据填充到promise对象中(意味着我们获取到了response,不管这个response的结果是成功或者是失败)。
  • promise被拒绝——通过执行某个动作后,不能获取到response(例如通过访问API获取服务器数据,但是服务器一直不能返回数据)。

为什么需要promise

我们需要promise是因为需要根据返回的结果(或者不返回结果)做出决定,下面的用一个例子说明。
我们的程序通过访问服务器API获取客户列表。
如果获取到response返回数据后,将数据显示到屏幕中;
如果不能获取到response返回数据时,提示用户。

使用$q service 处理promise

  angularjs中提供了$q 处理异步请求并且可以获得API的返回值。其真正出彩的地方是用户可以自定义promise。
看一个简单的例子。
var deferred = $q.defer();
// deferred 中包含了带有返回值的promise
// 解析带有返回值的promise使用.resolve
deferred.resolve(data);
// 解析被拒绝的promise 使用 .reject
deferred.reject(error);
现在,看一下angularjs如何具体实现。
app.service("githubService", function ($http, $q) {

    var deferred = $q.defer();

    this.getAccount = function () {
        return $http.get('https://api.github.com/users/haroldrv')
            .then(function (response) {
                // promise is fulfilled
                deferred.resolve(response.data);
                // promise is returned
                return deferred.promise;
            }, function (response) {
                // the following line rejects the promise 
                deferred.reject(response);
                // promise is returned
                return deferred.promise;
            })
        ;
    };
});
最终,angularjs controller中使用该service并且显示结果或提示用户数据不能返回。
app.controller("promiseController", function ($scope, $q, githubService) {

    githubService.getAccount()
        .then(
            function (result) {
                // promise was fullfilled (regardless of outcome)
                // checks for information will be peformed here
                $scope.account = result;
            },
            function (error) {
                // handle errors here
                console.log(error.statusText);
            }
        );
});




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值