AngularJS promise()
实例说明一
<!DOCTYPE html> <html ng-app="my-app"> <head> <meta charset="utf-8"> <title>JS Bin</title> <script src="http://apps.bdimg.com/libs/angular.js/1.4.0-beta.4/angular.min.js"></script> </head> <body> <div ng-controller="myctrl"></div> <script> angular.module("my-app",[]).controller("myctrl",['$q','$log',function($q,$log){ var deferred = $q.defer(); deferred.resolve(1); var promiseA = deferred.promise; promiseA .then(function(val){$log.info(val);return $q.reject(15);}) .then(function(val){$log.info(val);return ++val;}) .then(function(val){$log.info(val);return ++val;}) .then(function(val){$log.info(val);return ++val;}) .then( function(val){$log.info(val);return ++val;}, function(val){$log.info(val)} ); //------ $q.when('I Love you!') .then(function(value){$log.info(value)}); //------ $q.when($q.reject('I Hate you!')) .then(null,function(value){$log.info(value)}); //------ var promiseAA = $q.when('I Love you!'); var promiseB = $q.when('Love story!'); var promiseC = $q.when("Let't get wet!"); /*****/ $q.all([promiseAA,promiseB,promiseC]). then(function(value){ $log.info(value);}) .then(function(value){$log.info(value);}) .then(function(value){$log.info(value);}) /******/ }]) </script> </body> </html>
http://segmentfault.com/a/1190000000402555
http://www.thinksaas.cn/group/topic/264600/
HTML;
<!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="http://apps.bdimg.com/libs/angular.js/1.4.0-beta.4/angular.min.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 }; }]);
http://jsbin.com/cejuju/edit?html,js,output