全部文章
- 簡(jiǎn)介
- 基礎(chǔ)部分
- 進(jìn)階部分
- API 說(shuō)明
以下是對(duì)
PromiseKit
的README.md
的翻譯。
Promise 的可組合特性使得其變得非常有用。這使得復(fù)雜的異步操作變得安全,取代了傳統(tǒng)實(shí)現(xiàn)方式的麻煩。
調(diào)用鏈(Chaining)
最通用的模式就是使用調(diào)用鏈 Chaining:
firstly {
fetch()
}.then {
map($0)
}.then {
set($0)
return animate()
}.ensure {
// something that should happen whatever the outcome
}.catch {
handle(error: $0)
}
如果你在 then 中返回一個(gè) promise,下一個(gè) then 將會(huì)在繼續(xù)執(zhí)行之前等待這個(gè) promise。這就是 promise 的本質(zhì)。
鏈接 Promise 非常容易。在異步系統(tǒng)上,如果使用回調(diào)方式會(huì)產(chǎn)生很多意大利面式的代碼,而且難于重構(gòu),Promsie 都可以避免這些困擾。
Promise 的 API
Promsie 是可鏈接的,所以應(yīng)該將接收一個(gè)完成時(shí)回調(diào)的 block 替換為返回一個(gè) Promise。
class MyRestAPI {
func user() -> Promise<User> {
return firstly {
URLSession.shared.dataTask(.promise, with: url)
}.compactMap {
try JSONSerialization.jsonObject(with: $0.data) as? [String: Any]
}.map { dict in
User(dict: dict)
}
}
func avatar() -> Promise<UIImage> {
return user().then { user in
URLSession.shared.dataTask(.promise, with: user.imageUrl)
}.compactMap {
UIImage(data: $0.data)
}
}
}
這樣,在不破壞原有架構(gòu)的基礎(chǔ)上,異步鏈可以讓 App 中的代碼變得整潔,且無(wú)縫的連接在一起。
注意:我們也為 Alamofire 提供了 Promise。
后臺(tái)任務(wù)
class MyRestAPI {
func avatar() -> Promise<UIImage> {
let bgq = DispatchQueue.global(qos: .userInitiated)
return firstly {
user()
}.then(on: bgq) { user in
URLSession.shared.dataTask(.promise, with: user.imageUrl)
}.compactMap(on: bgq) {
UIImage(data: $0)
}
}
}
所有的 PromiseKit 處理程序都提供了 on 參數(shù),用來(lái)指定在哪個(gè)調(diào)度隊(duì)列上運(yùn)行處理程序。默認(rèn)是在主隊(duì)列上進(jìn)行處理。
PromiseKit 是完全線程安全的。
提示:在 background 隊(duì)列中使用 then,map,compactMap 時(shí),請(qǐng)謹(jǐn)慎操作。請(qǐng)參閱 PromiseKit.conf。請(qǐng)注意,我們建議僅針對(duì) map 相關(guān)的方法修改隊(duì)列,所以 done 和 catch 會(huì)繼續(xù)運(yùn)行在主隊(duì)列上。這通常符合你的想法。
失敗鏈
如果一個(gè) error 發(fā)生在鏈中間,只需要拋出一個(gè) error:
firstly {
foo()
}.then { baz in
bar(baz)
}.then { result in
guard !result.isBad else { throw MyError.myIssue }
//…
return doOtherThing()
}
這個(gè) error 將會(huì)傳遞到下一個(gè) catch 處理程序中。
由于 Promise 可以處理拋出異常的情況,所以你不需要用 do 代碼塊去包住一個(gè)會(huì)拋出異常的方法,除非你想在此處處理異常:
foo().then { baz in
bar(baz)
}.then { result in
try doOtherThing()
}.catch { error in
// if doOtherThing() throws, we end up here
}
提示:為了不把心思放在定義一個(gè)優(yōu)秀的全局 error Enum,Swift 允許在一個(gè)方法內(nèi)定義一個(gè)內(nèi)聯(lián)的 enum Error,這在編程實(shí)踐中并不好,但優(yōu)于不拋出異常。
異步抽象
var fetch = API.fetch()
override func viewDidAppear() {
fetch.then { items in
//…
}
}
func buttonPressed() {
fetch.then { items in
//…
}
}
func refresh() -> Promise {
// ensure only one fetch operation happens at a time
// 確保同一時(shí)間只有一個(gè) fetch 操作在執(zhí)行
if fetch.isResolved {
startSpinner()
fetch = API.fetch().ensure {
stopSpinner()
}
}
return fetch
}
使用 Promise 時(shí),你不需要操心異步操作何時(shí)結(jié)束。直接把它當(dāng)成已經(jīng)結(jié)束就行了
如上所示,你可以在 promise 上調(diào)用任意次數(shù)的 then。所有的 block 將會(huì)按照他們的添加順序被執(zhí)行。
鏈數(shù)組
當(dāng)需要對(duì)一個(gè)數(shù)組中的數(shù)據(jù)執(zhí)行一系列的操作任務(wù)時(shí):
// fade all visible table cells one by one in a “cascading” effect
var fade = Guarantee()
for cell in tableView.visibleCells {
fade = fade.then {
UIView.animate(.promise, duration: 0.1) {
cell.alpha = 0
}
}
}
fade.done {
// finish
}
或者你有一個(gè)返回 Promise 閉包的數(shù)組:
var foo = Promise()
for nextPromise in arrayOfClosuresThatReturnPromises {
foo = foo.then(nextPromise)
// ^^ you rarely would want an array of promises instead, since then
// they have all already started, you may as well use `when()`
}
foo.done {
// finish
}
注意:你通常會(huì)使用 when(),因?yàn)?when 執(zhí)行時(shí),所有組成的 Promise 是并行的,所以執(zhí)行速度非常快。上面這種模式適用于任務(wù)必須按順序執(zhí)行。比如上面的動(dòng)畫(huà)例子。
注意:我們還提供了 when(concurrently:),在需要同時(shí)執(zhí)行多個(gè) Promise 時(shí)可以使用。
超時(shí) Timeout
let fetches: [Promise<T>] = makeFetches()
let timeout = after(seconds: 4)
race(when(fulfilled: fetches).asVoid(), timeout).then {
//…
}
race
將會(huì)在監(jiān)控的任何一個(gè) Promise 完成時(shí)繼續(xù)執(zhí)行。
確保傳入 race 的 Promise 有相同的類型。為了確保這一點(diǎn),一個(gè)簡(jiǎn)單的方法就是使用 asVoid()
。
注意:如果任何組成的 Promise 失敗,race 將會(huì)跟著失敗。
最短持續(xù)時(shí)間
有時(shí)你需要一項(xiàng)至少持續(xù)指定時(shí)間的任務(wù)。(例如:你想要顯示一個(gè)進(jìn)度條,如果顯示時(shí)間低于 0.3 秒,這個(gè) UI 的顯示將會(huì)讓用戶措手不及。)<br />
let waitAtLeast = after(seconds: 0.3)
firstly {
foo()
}.then {
waitAtLeast
}.done {
//…
}
因?yàn)槲覀冊(cè)?foo() 后面添加了一個(gè)延遲,所以上面的代碼有效的解決了問(wèn)題。在等待 Promise 的時(shí)間時(shí),要么它已經(jīng)超時(shí),要么等待 0.3 秒剩余的時(shí)間,然后繼續(xù)執(zhí)行此鏈。
取消
Promise 沒(méi)有提供取消功能,但是提供了一個(gè)符合 CancellableError 協(xié)議的 error 類型來(lái)支持取消操作。
func foo() -> (Promise<Void>, cancel: () -> Void) {
let task = Task(…)
var cancelme = false
let promise = Promise<Void> { seal in
task.completion = { value in
guard !cancelme else { return reject(PMKError.cancelled) }
seal.fulfill(value)
}
task.start()
}
let cancel = {
cancelme = true
task.cancel()
}
return (promise, cancel)
}
Promise 沒(méi)有提供取消操作,因?yàn)闆](méi)人喜歡不受自己控制的代碼可以取消自己的操作。除非,你確實(shí)需要這種操作。在你想要支持取消操作時(shí),事實(shí)上取消的操作取決于底層的任務(wù)是否支持取消操作。PromiseKit 提供了取消操作的原始函數(shù),但是不提供具體的 API。
調(diào)用鏈在被取消時(shí),默認(rèn)不會(huì)調(diào)用 catch 處理方法。但是,你可以根據(jù)實(shí)際情況捕獲取消操作。
foo.then {
//…
}.catch(policy: .allErrors) {
// cancelled errors are handled *as well*
}
重點(diǎn):取消一個(gè) Promise 不等于取消底層的異步任務(wù)。Promise 只是將異步操作進(jìn)行了包裝,他們無(wú)法控制底層的任務(wù)。如果你想取消一個(gè)底層的任務(wù),那你必須取消這個(gè)底層的任務(wù)(而不是 Promise)。
重試 / 輪詢(Retry / Polling)
func attempt<T>(maximumRetryCount: Int = 3, delayBeforeRetry: DispatchTimeInterval = .seconds(2), _ body: @escaping () -> Promise<T>) -> Promise<T> {
var attempts = 0
func attempt() -> Promise<T> {
attempts += 1
return body().recover { error -> Promise<T> in
guard attempts < maximumRetryCount else { throw error }
return after(delayBeforeRetry).then(on: nil, attempt)
}
}
return attempt()
}
attempt(maximumRetryCount: 3) {
flakeyTask(parameters: foo)
}.then {
//…
}.catch { _ in
// we attempted three times but still failed
}
大多數(shù)情況下,你可能需要提供上面的代碼,以便在發(fā)生特定類型的錯(cuò)誤時(shí)進(jìn)行重試。
包裝代理模式(delegate system)
在代理模式(delegate system)下,使用 Promise 需要格外小心,因?yàn)樗鼈儾灰欢嫒荨romise 僅完成一次,而大多數(shù)代理系統(tǒng)會(huì)多次的通知它們的代理。比如 UIButton,這也是為什么 PromiseKit 沒(méi)有給 UIButton 提供擴(kuò)展的原因。
何時(shí)去包裝一個(gè)代理,一個(gè)很好的例子就是當(dāng)你需要一個(gè) CLLocation
時(shí):
extension CLLocationManager {
static func promise() -> Promise<CLLocation> {
return PMKCLLocationManagerProxy().promise
}
}
class PMKCLLocationManagerProxy: NSObject, CLLocationManagerDelegate {
private let (promise, seal) = Promise<[CLLocation]>.pending()
private var retainCycle: PMKCLLocationManagerProxy?
private let manager = CLLocationManager()
init() {
super.init()
retainCycle = self
manager.delegate = self // does not retain hence the `retainCycle` property
promise.ensure {
// ensure we break the retain cycle
self.retainCycle = nil
}
}
@objc fileprivate func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
seal.fulfill(locations)
}
@objc func locationManager(_: CLLocationManager, didFailWithError error: Error) {
seal.reject(error)
}
}
// use:
CLLocationManager.promise().then { locations in
//…
}.catch { error in
//…
}
請(qǐng)注意:我們已經(jīng)提供了 CoreLocation 的這個(gè) Promise 擴(kuò)展,請(qǐng)看 https://github.com/PromiseKit/CoreLocation
恢復(fù) Recovery
有時(shí)我們不想要一個(gè)錯(cuò)誤的結(jié)果,而是提供一個(gè)默認(rèn)的結(jié)果:
CLLocationManager.requestLocation().recover { error -> Promise<CLLocation> in
guard error == MyError.airplaneMode else {
throw error
}
return .value(CLLocation.savannah)
}.done { location in
//…
}
請(qǐng)注意不要忽略所有的錯(cuò)誤。僅恢復(fù)哪些有意義的錯(cuò)誤。
Model View Controllers 的 Promises
class ViewController: UIViewController {
private let (promise, seal) = Guarantee<…>.pending() // use Promise if your flow can fail
func show(in: UIViewController) -> Promise<…> {
in.show(self, sender: in)
return promise
}
func done() {
dismiss(animated: true)
seal.fulfill(…)
}
}
// use:
ViewController().show(in: self).done {
//…
}.catch { error in
//…
}
這是我們目前最佳的實(shí)現(xiàn)方式,遺憾的是,他要求彈出的 view Controller 控制彈出操作,并且需要彈出的 view Controller 自己 dismiss 掉。
似乎沒(méi)有比 storyboard 更好的方式來(lái)解耦應(yīng)用程序的控制器。
保存之前的結(jié)果
假設(shè)有下面的代碼:
login().then { username in
fetch(avatar: username)
}.done { image in
//…
}
如何在 done 中同時(shí)獲取 username 和 image 呢?
通常的做法是嵌套:
login().then { username in
fetch(avatar: username).done { image in
// we have access to both `image` and `username`
}
}.done {
// the chain still continues as you'd expect
}
然而,這種嵌套會(huì)降低調(diào)用鏈的可讀性。我們應(yīng)該使用 swift 的元組 tuples 來(lái)代替:
login().then { username in
fetch(avatar: username).map { ($0, username) }
}.then { image, username in
//…
}
上面的代碼只是將 Promise<String>
映射為 Promise<(UIImage, String)>
。
等待多個(gè) Promise,不論他們的結(jié)果
使用 when(resolved:)
:
when(resolved: a, b).done { (results: [Result<T>]) in
// `Result` is an enum of `.fulfilled` or `.rejected`
}
// ^^ cannot call `catch` as `when(resolved:)` returns a `Guarantee`
通常,你并不會(huì)用到這個(gè)。很多人會(huì)過(guò)度使用這個(gè)方法,因?yàn)檫@可以忽略異常。他們真正需要的應(yīng)該是對(duì)其中的 Promise 進(jìn)行恢復(fù)。當(dāng)錯(cuò)誤發(fā)生時(shí),我們應(yīng)該去處理它,而不是忽略它。