Angular学习:$q
原文地址:https://docs.angularjs.org/api/ng/service/$q。 $q 1.- $qProvider 2.- service in moduleng A service thathelps you run functions asynchronously,and use their return values (orexceptions) when they are done processing. 一个服务,可以帮助您异步运行函数并在完成处理后使用其返回值(或异常)。 This is aPromises/A+-compliantimplementation of promises/deferred objects inspired byKris Kowal's Q. 这是Promise / A +兼容的promise / deferred对象的实现,灵感来自Kris Kowal's Q。 $q can be usedin two fashions --- one which is more similar to Kris Kowal's Q or jQuery'sDeferred implementations,and the other which resembles ES6 (ES2015) promisesto some degree. $q可以以两种方式使用 --- 一种更类似于Kris Kowal的Q或jQuery的Deferred实现,另一种在某种程度上类似于ES6(ES2015)的promises。 $q constructor The streamlinedES6 style promise is essentially just using $q as a constructor which takesaresolverfunction as the first argument. Thisis similar to the native Promise implementation from ES6,seeMDN. 流线化的ES6风格的promise本质上只是使用$q作为一个构造函数,它接受一个resolver函数作为第一个参数。这类似于ES6的原生的Promise实现,请参阅MDN。 While theconstructor-style use is supported,not all of the supporting methods from ES6promises are available yet. 虽然构造函数风格的使用被支持,但并不是所有的ES6 promises支持的方法都可用。 It can be usedlike so: 它可以被类似这样使用: // for the purpoSEOf this example let's assume that variables `$q` and `okToGreet` // are available inthe current lexical scope (they could have been injected or passed in).
functionasyncGreet(name) { // perform some asynchronous operation,resolve or reject the promise when appropriate. return $q(function(resolve,reject) { setTimeout(function() { if (okToGreet(name)) { resolve('Hello,' + name + '!'); } else { reject('Greeting ' + name + ' is notallowed.'); } },1000); }); }
var promise =asyncGreet('Robin Hood'); promise.then(function(greeting){ alert('Success: ' + greeting); },function(reason){ alert('Failed: ' + reason); }); Note:progress/notify callbacks are not currently supported via the ES6-styleinterface. 注意:progress/notify回调函数当前不被通过ES6样式的接口支持。 Note: unlike ES6behavior,an exception thrown in the constructor function will NOT implicitlyreject the promise. 注意:不像ES6的行为,一个异常会被抛出在当前的构造函数中,这将不会隐含reject这个promise。 However,themore traditional CommonJS-style usage is still available,and documented below. 然后,更传统的CommonJS-style的使用是仍旧可用的,并且展示在下面。 The CommonJS Promise proposaldescribes apromise as an interface for interacting with an object that represents theresult of an action that is performed asynchronously,and may or may not befinished at any given point in time. The CommonJS Promise proposal描述了一个promise作为一个接口来和一个对象互动,这个对象代表着一个行为的结果,这个行为是异步执行的,并且可能会或者可能不会在任意指定的点上及时地被结束。 From theperspective of dealing with error handling,deferred and promise APIs are toasynchronous programming whattry,catchandthrowkeywords are to synchronousprogramming. 从处理错误的角度来看,deferred和promise API是针对异步编程的,而try、catch和throw是针对同步编程的。 // for the purpoSEOf this example let's assume that variables `$q` and `okToGreet` // are available inthe current lexical scope (they could have been injected or passed in).
function asyncGreet(name){ var deferred = $q.defer();
setTimeout(function() { deferred.notify('About to greet ' + name + '.');
if (okToGreet(name)) { deferred.resolve('Hello,' + name + '!'); } else { deferred.reject('Greeting ' + name + ' is notallowed.'); } },1000);
return deferred.promise; }
var promise =asyncGreet('Robin Hood'); promise.then(function(greeting){ alert('Success: ' + greeting); },function(reason){ alert('Failed: ' + reason); },function(update){ alert('Got notification:' + update); }); At first itmight not be obvious why this extra complexity is worth the trouble. The payoffcomes in the way of guarantees that promise and deferred APIs make,seehttps://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. 首先,这额外的复杂性带来的麻烦是值得的,这一点并不明显。回报来自于promise 和deferred API完成的一些保证。可以参考:https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md。 Additionally thepromise api allows for composition that is very hard to do with the traditionalcallback (CPS) approach. For moreon this please see theQ documentationespeciallythe section on serial or parallel joining of promises. 额外的,这promise API允许合成,而这是传统的回调(CPS)方法很难完成的。更多的信息请参看Qdocumentation,特别是promise的串行或者并行的连接那一章节。 The Deferred API A new instanceof deferred is constructed by calling$q.defer(). 一个新的deferred的实例是由调用$q.defer()来构造的。 The purpose ofthe deferred object is to expose the associated Promise instance as well asAPIs that can be used for signaling the successful or unsuccessful completion,as well as the status of the task. Deferred对象的目的是暴露出相关联的Promise实例,就像那些可以被用于去发出成功或者不成功完成的信号的API一样,就像任务的状态一样。 Methods 方法
Properties
The Promise API A new promiseinstance is created when a deferred instance is created and can be retrieved bycallingdeferred.promise. 一个新的promise实例被创建,在一个deferred实例被创建,并且通过调用deferred.promise而获取到。 The purpose ofthe promise object is to allow for interested parties to get access to theresult of the deferred task when it completes. 这个promise对象的目的是允许有兴趣的部分去可以访问deferred task的结果—当这个task完成的时候。 Methods
This methodreturns a new promisewhich is resolved or rejectedvia the return value of thesuccessCallback,errorCallback(unless that value is a promise,in which case it isresolved with the value which is resolved in that promise usingpromise chaining). Italso notifies via the return value of thenotifyCallbackmethod.The promise cannot be resolved or rejected from the notifyCallback method. TheerrorCallback and notifyCallback arguments are optional.
Chaining promises Because callingthethenmethod of a promise returns a new derivedpromise,it is easily possible to create a chain of promises: promiseB =promiseA.then(function(result) { return result + 1; });
// promiseB will beresolved immediately after promiseA is resolved and its value // will be theresult of promiseA incremented by 1 It is possibleto create chains of any length and since a promise can be resolved with anotherpromise (which will defer its resolution further),it is possible topause/defer resolution of the promises at any point in the chain. This makes itpossible to implement powerful APIs like $http's response interceptors. Differences between KrisKowal's Q and $q There are twomain differences:
Testing it('should simulatepromise',inject(function($q,$rootScope) { var deferred = $q.defer(); var promise = deferred.promise; var resolvedValue;
promise.then(function(value) { resolvedValue= value; }); expect(resolvedValue).toBeUndefined();
// Simulate resolving of promise deferred.resolve(123); // Note that the 'then' function doesnot get called synchronously. // This is because we want the promiseAPI to always be async,whether or not // it got called synchronously orasynchronously. expect(resolvedValue).toBeUndefined();
// Propagate promise resolution to'then' functions using $apply(). $rootScope.$apply(); expect(resolvedValue).toEqual(123); })); Dependencies
Usage $q(resolver); Arguments
Returns
Methods
Creates aDeferredobjectwhich represents a task which will finish in the future. Returns
Creates a promise that is resolved as rejected with the specifiedreason. This api should be used to forward rejection in a chain of promises. Ifyou are dealing with the last promise in a promise chain,you don't need toworry about it. When comparing deferreds/promises to the familiar behavior oftry/catch/throw,think ofrejectasthethrowkeyword in JavaScript. This alsomeans that if you "catch" an error via a promise error callback andyou want to forward the error to the promise derived from the current promise,you have to "rethrow" the error by returning a rejection constructedviareject. promiseB =promiseA.then(function(result) { // success: dosomething and resolve promiseB // with the old or a new result return result; },function(reason){ // error: handle the error if possibleand //resolve promiseB with newPromiSEOrValue, //otherwise forward the rejection to promiseB if (canHandle(reason)) { // handle the error and recover return newPromiSEOrValue; } return $q.reject(reason); }); Parameters
Returns
Wraps an object that might be a value or a (3rd party) then-able promiseinto a $q promise. This is useful when you are dealing with an object thatmight or might not be a promise,or if the promise comes from a source that can'tbe trusted. Parameters
Returns
Alias ofwhento maintainnaming consistency with ES6. Parameters
Returns
Combines multiple promises into a single promise that is resolved when allof the input promises are resolved. Parameters
Returns
Returns a promise that resolves or rejects as soon as one of thosepromises resolves or rejects,with the value or reason from that promise. Parameters
Returns
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |