Intro
Promise 是什么?根据维基百科的定义
They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is not yet complete.
很多编程语言都有 Promise 的库,甚至有些语言,如 Javascript,甚至集成到了标准库中。作为 iOS 开发者,也避免不了写大量回调的代码,然而这样直接的写法在复杂的异步场景下,会带来可理解性和可维护性上的挑战。Promise 作为一个比较轻量级的抽象,在 OOP 的包装下,通过一些简单的扩展实现,可以很方便地处理一些异步场景,如then:
(链式调用),all:
(等待多个异步结果),retry:
(重试)等。
FBLPromise
FBLPromises 就是在 Objective-C 下的一个 Promise 库。下面以它的源码作为分析,其实核心代码只有两个函数。
在 FBLPromise 对象中,有这些实例变量和静态变量。
static dispatch_queue_t gFBLPromiseDefaultDispatchQueue;
@implementation FBLPromise {
/** Current state of the promise. */
FBLPromiseState _state;
/**
Set of arbitrary objects to keep strongly while the promise is pending.
Becomes nil after the promise has been resolved.
*/
NSMutableSet *__nullable _pendingObjects;
/**
Value to fulfill the promise with.
Can be nil if the promise is still pending, was resolved with nil or after it has been rejected.
*/
id __nullable _value;
/**
Error to reject the promise with.
Can be nil if the promise is still pending or after it has been fulfilled.
*/
NSError *__nullable _error;
/** List of observers to notify when the promise gets resolved. */
NSMutableArray<FBLPromiseObserver> *_observers;
}
...