QProvider 简介
源码里是这么描述的:
A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.
大概意思是帮助你异步执行方法,且当他们执行完后可以使用他们的返回值。
This is an implementation of promises/deferred objects inspired by Kris Kowal’s Q.
这是一个 promises/deferred 对象的实现,灵感来自于 Kris Kowal’s Q
QProvider 用法
下面的例子假设$q和asyncGreet在当前作用域内是有效的.
1 | function asyncGreet(name) { |
下面我们深入源码内部去一探究竟:
$QProvider 定义
1 | function $QProvider() { |
由之前 cacheFactory的分析
,再结合上面源码我们就知道 注入$q时调用了qFactory工厂方法:
qFactory
1 | function qFactory(nextTick, exceptionHandler) { |
调用then方法时实际上是新建一个defer对象放入pending数组,在调用defer.resolve的时候
去调度这个数组中的元素,也就是任务.
resolve 方法
1 | extend(Deferred.prototype, { |
scheduleProcessQueue 方法
1 | //传入promise的state对象 |
processQueue 方法
实际最终处理的还是processQueue函数,里面循环调用pending数组1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25function processQueue(state) {
var fn, deferred, pending;
pending = state.pending;
state.processScheduled = false;
state.pending = undefined;
for (var i = 0, ii = pending.length; i < ii; ++i) {
//获取pending数组的元素 元素本身也是数组
deferred = pending[i][0];
fn = pending[i][state.status];
try {
if (isFunction(fn)) {
deferred.resolve(fn(state.value));
} else if (state.status === 1) {
deferred.resolve(state.value);
} else {
deferred.reject(state.value);
}
} catch (e) {
deferred.reject(e);
exceptionHandler(e);
}
}
}
参考资料: