原文地址:https://docs.angularjs.org/api/ng/service/$q。html
$qhtml5
1. - $qProvidergit
2. - service in module ngangularjs
A service thathelps you run functions asynchronously, and use their return values (orexceptions) when they are done processing.es6
一个服务,能够帮助您异步运行函数并在完成处理后使用其返回值(或异常)。github
This is a Promises/A+-compliantimplementation of promises/deferred objects inspired by Kris Kowal's Q.编程
这是Promise / A +兼容的promise / deferred对象的实现,灵感来自 Kris Kowal's Q。api
$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.promise
$q能够以两种方式使用 --- 一种更相似于Kris Kowal的Q或jQuery的Deferred实现,另外一种在某种程度上相似于ES6(ES2015)的promises。app
$q constructor
The streamlinedES6 style promise is essentially just using $q as a constructor which takesa resolver function as the first argument. Thisis similar to the native Promise implementation from ES6, see MDN.
流线化的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 proposal describes 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 what try, catchand throw keywords 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, see https://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 the Q documentation especiallythe 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 bycalling deferred.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 method returns a new promise which is resolved or rejectedvia the return value of the successCallback, errorCallback(unless that value is a promise, in which case it isresolved with the value which is resolved in that promise using promise chaining). Italso notifies via the return value of the notifyCallback method.The promise cannot be resolved or rejected from the notifyCallback method. TheerrorCallback and notifyCallback arguments are optional.
Chaining promises
Because callingthe then method 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
Param |
Type |
Details |
resolver |
Function which is responsible for resolving or rejecting the newly created promise. The first parameter is a function which resolves the promise, the second parameter is a function which rejects the promise. |
Returns
The newly created promise. |
Methods
Creates a Deferred objectwhich represents a task which will finish in the future.
Returns
Returns a new instance of deferred. |
Creates a promise that is resolved as rejected with the specified reason. 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 of reject asthe throw keyword 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 constructedvia reject.
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
Param |
Type |
Details |
reason |
Constant, message, exception or an object representing the rejection reason. |
Returns
Returns a promise that was already resolved as rejected with the reason. |
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
Param |
Type |
Details |
value |
Value or a promise |
|
successCallback (optional) |
||
errorCallback (optional) |
||
progressCallback (optional) |
Returns
Returns a promise of the passed value or promise |
Alias of when to maintainnaming consistency with ES6.
Parameters
Param |
Type |
Details |
value |
Value or a promise |
|
successCallback (optional) |
||
errorCallback (optional) |
||
progressCallback (optional) |
Returns
Returns a promise of the passed value or promise |
Combines multiple promises into a single promise that is resolved when allof the input promises are resolved.
Parameters
Param |
Type |
Details |
promises |
An array or hash of promises. |
Returns
Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. |
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
Param |
Type |
Details |
promises |
An array or hash of promises. |
Returns
a promise that resolves or rejects as soon as one of the promises resolves or rejects, with the value or reason from that promise. |