第一次接触的是 q . w h e n 。 后 来 在 业 务 中 使 用 了 三 四 次 q.when。后来在业务中使用了三四次 q.when。后来在业务中使用了三四次q.all.,这几次业务场景都是需要同时处理请求。
其实网上介绍$q用法的文章挺多的。写的也都很好。印象比较深的是一篇文章中,博主用定制家具的例子,比较详细的介绍了$q的用法。所以如果之前接触过异步、同步的概念,或者使用过ES6的promise特性,理解起来$q都很容易。那这篇文章就试着了解下angularjs中该服务的实现源码。
v1.5.8版本的angularjs源码中关于$q服务的介绍:
$q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred implementations, and the other which resembles ES6 (ES2015) promises to some degree.
resolver
* // for the purpose of this example let's assume that variables `$q` and `okToGreet`
* // are available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(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 not allowed.');
* }
* }, 1000);
* });
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* });
*
commonjs-style usage(使用过的方式)
* // for the purpose of this example let's assume that variables `$q` and `okToGreet`
* // are available in the 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 not allowed.');
* }
* }, 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);
* });
*
源码:
下面代码解释了qFactory中定义了哪些内容:
var $Q = function Q(resolver) { // 不是很明白这里Q什么?
if (!isFunction(resolver)) {
throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
}
var deferred = new Deferred(); // Deferred构造函数,在源码中有定义。
function resolveFn(value) {
deferred.resolve(value);
}
function rejectFn(reason) {
deferred.reject(reason);
}
resolver(resolveFn, rejectFn);
return deferred.promise;
};
// Let's make the instanceof operator work for promises, so that
// `new $q(fn) instanceof $q` would evaluate to true.
$Q.prototype = Promise.prototype;
$Q.defer = defer;
$Q.reject = reject;
$Q.when = when;
$Q.resolve = resolve;
$Q.all = all;
return $Q; // 整个qFactory最后返回的内容。
$q.defer()
.var defer = function() {
var d = new Deferred();
//Necessary to support unbound execution :/
d.resolve = simpleBind(d, d.resolve);
d.reject = simpleBind(d, d.reject);
d.notify = simpleBind(d, d.notify);
return d;
};
Deferred对象的构造方法:
deferred支持的API:
resolve(value)
— resolves the derived promise with the value
. If the value is a rejection constructed via $q.reject
, the promise will be rejected instead.
defered.resolve(value)
reject(reason)
— rejects the derived promise with the reason
. This is equivalent to resolving it with a rejection constructed via $q.reject
.
defered.reject(reason)
notify(value)
- provides updates on the status of the promise’s execution. This may be called multiple times before the promise is either resolved or rejected.
Properties
promise — promise object associated with this deferred.
deferred.promise
.promise实例方法:
then(successCallback, errorCallback, notifyCallback)
regardless of when the promise was or will be resolved or rejected, then
calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.successCallback
, errorCallback
(unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chainingnotifyCallback
method. The promise cannot be resolved or rejected from the notifyCallback method.catch(errorCallback)
shorthand for promise.then(null, errorCallback)
finally(callback, notifyCallback)
allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved.