【问题标题】:How to map Promise<T> to Guarantee<Bool>?如何将 Promise<T> 映射到 Guarantee<Bool>?
【发布时间】:2019-06-25 04:34:20
【问题描述】:

我有一个 Promise&lt;T&gt;,我想将其转换为 Guarantee&lt;Bool&gt;,其中 true 表示承诺已实现,如果被拒绝则为 false。

我设法做到了这一点

  return getPromise()
    .map { _ in true }
    .recover { _ in Guarantee.value(false) }

我想知道是否有更简洁的方法来做到这一点。

【问题讨论】:

  • 你可以在 promise 中传递 bool 值吗?

标签: ios promisekit


【解决方案1】:

扩展原始代码和此处的答案,我将明确地为Void Promises 进行扩展,并保持命名与 PromiseKit 更加一致:

extension Promise where T == Void {
    func asGuarantee() -> Guarantee<Bool> {
        self.map { true }.recover { _ in .value(false) }
    }
}

【讨论】:

    【解决方案2】:

    您可以如下扩展promise,以便使用

    中提到的方便使用
    extension Promise {
    
        func guarantee() -> Guarantee<Bool> {
            return Guarantee<Bool>(resolver: { [weak self] (body) in
                self?.done({ (result) in
                    body(true)
                }).catch({ (error) in
                    body(false)
                })
            })
        }
    }
    

    用法:

    // If you want to execute a single promise and care about success only.
    getPromise().guarantee().done { response in
        // Promise success handling here.
    }
    
    // For chaining multiple promises
    getPromise().guarantee().then { bool -> Promise<Int> in
            return .value(20)
        }.then { integer -> Promise<String> in
            return .value("Kamran")
        }.done { name in
            print(name)
        }.catch { e in
            print(e)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多