PromiseKit 的常见模式

全部文章

以下是对 PromiseKitREADME.md 的翻译。

Promise 的可组合特性使得其变得非常有用。这使得复杂的异步操作变得安全,取代了传统实现方式的麻烦。

调用链(Chaining)

最通用的模式就是使用调用链 Chaining:

firstly {
    fetch()
}.then {
    map($0)
}.then {
    set($0)
    return animate()
}.ensure {
    // something that should happen whatever the outcome
}.catch {
    handle(error: $0)
}

如果你在 then 中返回一个 promise,下一个 then 将会在继续执行之前等待这个 promise。这就是 promise 的本质。

链接 Promise 非常容易。在异步系统上,如果使用回调方式会产生很多意大利面式的代码,而且难于重构,Promsie 都可以避免这些困扰。

Promise 的 API

Promsie 是可链接的,所以应该将接收一个完成时回调的 block 替换为返回一个 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)
        }
    }
}

这样,在不破坏原有架构的基础上,异步链可以让 App 中的代码变得整洁,且无缝的连接在一起。

注意:我们也为 Alamofire 提供了 Promise。

后台任务

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 参数,用来指定在哪个调度队列上运行处理程序。默认是在主队列上进行处理。

PromiseKit 是完全线程安全的。

提示:在 background 队列中使用 then,map,compactMap 时,请谨慎操作。请参阅 PromiseKit.conf。请注意,我们建议仅针对 map 相关的方法修改队列,所以 done 和 catch 会继续运行在主队列上。这通常符合你的想法。

失败链

如果一个 error 发生在链中间,只需要抛出一个 error:

firstly {
    foo()
}.then { baz in
    bar(baz)
}.then { result in
    guard !result.isBad else { throw MyError.myIssue }
    //…
    return doOtherThing()
}

这个 error 将会传递到下一个 catch 处理程序中。

由于 Promise 可以处理抛出异常的情况,所以你不需要用 do 代码块去包住一个会抛出异常的方法,除非你想在此处处理异常:

foo().then { baz in
    bar(baz)
}.then { result in
    try doOtherThing()
}.catch { error in
    // if doOtherThing() throws, we end up here
}

提示:为了不把心思放在定义一个优秀的全局 error Enum,Swift 允许在一个方法内定义一个内联的 enum Error,这在编程实践中并不好,但优于不抛出异常。

异步抽象

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
    // 确保同一时间只有一个 fetch 操作在执行
    if fetch.isResolved {
        startSpinner()
        fetch = API.fetch().ensure {
            stopSpinner()
        }
    }
    return fetch
}

使用 Promise 时,你不需要操心异步操作何时结束。直接把它当成已经结束就行了

如上所示,你可以在 promise 上调用任意次数的 then。所有的 block 将会按照他们的添加顺序被执行。

链数组

当需要对一个数组中的数据执行一系列的操作任务时:

// 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
}

或者你有一个返回 Promise 闭包的数组:

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
}

注意:你通常会使用 when(),因为 when 执行时,所有组成的 Promise 是并行的,所以执行速度非常快。上面这种模式适用于任务必须按顺序执行。比如上面的动画例子。

注意:我们还提供了 when(concurrently:),在需要同时执行多个 Promise 时可以使用。

超时 Timeout

let fetches: [Promise<T>] = makeFetches()
let timeout = after(seconds: 4)

race(when(fulfilled: fetches).asVoid(), timeout).then {
    //…
}

race 将会在监控的任何一个 Promise 完成时继续执行。

确保传入 race 的 Promise 有相同的类型。为了确保这一点,一个简单的方法就是使用 asVoid()

注意:如果任何组成的 Promise 失败,race 将会跟着失败。

最短持续时间

有时你需要一项至少持续指定时间的任务。(例如:你想要显示一个进度条,如果显示时间低于 0.3 秒,这个 UI 的显示将会让用户措手不及。)<br />

let waitAtLeast = after(seconds: 0.3)

firstly {
    foo()
}.then {
    waitAtLeast
}.done {
    //…
}

因为我们在 foo() 后面添加了一个延迟,所以上面的代码有效的解决了问题。在等待 Promise 的时间时,要么它已经超时,要么等待 0.3 秒剩余的时间,然后继续执行此链。

取消

Promise 没有提供取消功能,但是提供了一个符合 CancellableError 协议的 error 类型来支持取消操作。

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 没有提供取消操作,因为没人喜欢不受自己控制的代码可以取消自己的操作。除非,你确实需要这种操作。在你想要支持取消操作时,事实上取消的操作取决于底层的任务是否支持取消操作。PromiseKit 提供了取消操作的原始函数,但是不提供具体的 API。

调用链在被取消时,默认不会调用 catch 处理方法。但是,你可以根据实际情况捕获取消操作。

foo.then {
    //…
}.catch(policy: .allErrors) {
    // cancelled errors are handled *as well*
}

重点:取消一个 Promise 不等于取消底层的异步任务。Promise 只是将异步操作进行了包装,他们无法控制底层的任务。如果你想取消一个底层的任务,那你必须取消这个底层的任务(而不是 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
}

大多数情况下,你可能需要提供上面的代码,以便在发生特定类型的错误时进行重试。

包装代理模式(delegate system)

在代理模式(delegate system)下,使用 Promise 需要格外小心,因为它们不一定兼容。Promise 仅完成一次,而大多数代理系统会多次的通知它们的代理。比如 UIButton,这也是为什么 PromiseKit 没有给 UIButton 提供扩展的原因。

何时去包装一个代理,一个很好的例子就是当你需要一个 CLLocation 时:

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
    //…
}

请注意:我们已经提供了 CoreLocation 的这个 Promise 扩展,请看 https://github.com/PromiseKit/CoreLocation

恢复 Recovery

有时我们不想要一个错误的结果,而是提供一个默认的结果:

CLLocationManager.requestLocation().recover { error -> Promise<CLLocation> in
    guard error == MyError.airplaneMode else {
        throw error
    }
    return .value(CLLocation.savannah)
}.done { location in
    //…
}

请注意不要忽略所有的错误。仅恢复哪些有意义的错误。

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
    //…
}

这是我们目前最佳的实现方式,遗憾的是,他要求弹出的 view Controller 控制弹出操作,并且需要弹出的 view Controller 自己 dismiss 掉。

似乎没有比 storyboard 更好的方式来解耦应用程序的控制器。

保存之前的结果

假设有下面的代码:

login().then { username in
    fetch(avatar: username)
}.done { image in
    //…
}

如何在 done 中同时获取 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
}

然而,这种嵌套会降低调用链的可读性。我们应该使用 swift 的元组 tuples 来代替:

login().then { username in
    fetch(avatar: username).map { ($0, username) }
}.then { image, username in
    //…
}

上面的代码只是将 Promise<String> 映射为 Promise<(UIImage, String)>

等待多个 Promise,不论他们的结果

使用 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`

通常,你并不会用到这个。很多人会过度使用这个方法,因为这可以忽略异常。他们真正需要的应该是对其中的 Promise 进行恢复。当错误发生时,我们应该去处理它,而不是忽略它。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355