如何将Promise <T>映射到Guarantee <Bool>?

时间:2019-06-25 04:34:20

标签: ios promisekit

我有一个Promise<T>,我想转化为Guarantee<Bool>,其中true表示承诺已兑现,而false则表示被拒绝。

我设法使用

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

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

2 个答案:

答案 0 :(得分:0)

您可以按以下说明扩展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)
}

答案 1 :(得分:0)

扩展原始代码和此处的答案,我将为 Void Promise 明确扩展,并使命名与 PromiseKit 更加一致:

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