目录
在上节中,我们在http中使用了then 和 在ngResource中返回了一个'延迟对象'.
本节介绍一下angular中的promise.
我觉得可以把js中的promise比作c#中的Task 的await 以同步的时候 实现回调.
使用promise
我们先可以了解一下$q
的defer()
方法创建的对象具有哪些方法
resolve(value)
:用来执行deferred promise
,value
可以为字符串,对象等。reject(value)
:用来拒绝deferred promise
,value
可以为字符串,对象等。notify(value)
:获取deferred promise
的执行状态,然后使用这个函数来传递它。then(successFunc, errorFunc, notifyFunc)
:无论promise
是成功了还是失败了,当结果可用之后,then
都会立刻异步调用successFunc
,或者'errorFunc',在promise
被执行或者拒绝之前,notifyFunc
可能会被调用0到多次,以提供过程状态的提示。catch(errorFunc):抛出异常的时候,触发该函数.可以为整个then链提供一个统一异常处理.
finally(callback):总是会被执行,不管 promise 被处理或者被拒绝,起清理作用
1. 引用angular.js后,定义控制器,配置$q环境
<script src="Scripts/jquery-1.9.1.js"></script> <script> angular.module('myApp', []).controller('helloCtrl', ['$scope', '$q', '$timeout', function (scope, q, timeout) { } </script>
2. 定义一个func函数.
function func() { var defer = $q.defer();//创建1个defer对象 var promise = defer.promise;//获取promise对象 promise.then(function (e) { console.log('then1-success' + e); }, function (e) { console.log('then1-faild' + e); }, function (e) { console.log('then1-notice' + e); }).then(function (e) { console.log('then2-success' + e); throw "then2 exception"; }).catch(function (e) { console.log('catch' + e); }).finally(function (e) { console.log('finally' + e); }); defer.notify('通知1'); defer.notify('通知2'); defer.resolve('成功1'); defer.reject('失败1'); }
3. 触发func函数(绑定到scope上即可触发)
补充说明
- 在执行promise的resolve和reject方法时,表示异步结束.(所以此处没显示'失败1')
- then2中,e为undefined.原因是上个then方法中并没有return对象.(同样只能在successFunc, errorFunc中返回才有效)
- 如果上个then方法返回一个promise对象,则then2会在promise异步结束时才触发,并获取到异步结果.
为了更好的说明,这里演示一下then返回promise的情况.
function funcPromise() { var defer = q.defer(); var promise = defer.promise; promise.then(function() { var thenDefer = q.defer(); timeout(function() { thenDefer.resolve('thenDefer 成功'); //thenDefer.reject('thenDefer 失败');//会触发下个then的errorFunc }); return thenDefer.promise; }).then(function(e) { console.log('then2-success' + e); },function(e) { console.log('then2-faild' + e); }); defer.resolve(); }
$q.all
$q.all()
,允许你等待并行的 promise 处理,当所有的 promise 都被处理结束之后,调用共同的回调
scope.all = function () { q.all([getAjaxPromise(), getTimePromise()]).then(function () { console.log(arguments); }); }
getAjaxPromise 和 getTimePromise 函数都返回promise对象了
$q.when
$q.when(),可以将非promise标准的对象 提供给then函数.
scope.when = function() { q.when('hello').then(function(e) { console.log(e); }); q.when(getAjaxPromise()).then(function (e) { console.log(e); }); }
getAjaxPromise 是返回promise标准的 而'hello'是一个普通的字符串.
本文地址:http://neverc.cnblogs.com/p/5928285.html