码迷,mamicode.com
首页 > Web开发 > 详细

AngularJS promise的使用

时间:2015-10-04 12:18:10      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

 

<!doctype html>
<html ng-app="myApp">
<head>
  <link rel="stylesheet" href="http://cdn.jsdelivr.net/foundation/4.3.2/css/foundation.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js"></script> 
</head>
<body>
  
<h1>Open Pull Requests for Angular JS</h1>

<ul ng-controller="DashboardController">
  <li ng-repeat="pr in pullRequests">
    {{ pr.title }}
  </li>
</ul>
  
</body>
</html>

 

angular.module(‘myApp‘, [])

.controller(‘DashboardController‘, [
  ‘$scope‘, ‘GithubService‘,
    function($scope, GithubService) {
      GithubService.getPullRequests()
      .then(function(data) {
        $scope.pullRequests = data;
      });
}])
.factory(‘GithubService‘, [
  ‘$q‘, ‘$http‘,
    function($q, $http) {
      var getPullRequests = function() {
        var deferred = $q.defer();
        // Get list of open angular js pull requests from github
        $http.get(‘https://api.github.com/repos/angular/angular.js/pulls‘)
        .success(function(data) {
          deferred.resolve(data);
        })
        .error(function(reason) {
          deferred.reject(reason);
        });
        return deferred.promise;
      };

      return { // return factory object
        getPullRequests: getPullRequests
      };
}]);

 then:无论promise成功还是失败了,当结果可用之后,then都会立刻异步调用successFn或者errFn。这个方法始终用一个参数来调用回调函数:结果,或者是拒绝的理由。promise被执行或者拒绝之前notifyFn回调可能会被调用0到多次,以提供过程状态的提示。

then()方法总是返回一个新的promise,可以通过successFn或者errFn这样的返回值执行或者被拒绝。它也能通过notifyFn提供通知。

AngularJS promise的使用

标签:

原文地址:http://www.cnblogs.com/ByronWu12345/p/4854323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!