Search code examples
swiftgenericspromisekit

Invalid conversion of recover block, PromiseKit


This code

let promise: Promise<Supplier> = self.supplierController
                        .update(supplier: supplier)

let block: ((Error) throws -> Supplier) = { (error: Error) throws -> Supplier in
    let supplier: Supplier = supplier
    guard (error as NSError).code == 405 else {
        throw error
    }
    return supplier
}

let newPromise = 
promise
    .recover(block)
    .done { (_: Supplier) in
        changeCompanyIdAndAppendMessage()
    }

gives compile time error

invalid conversion from throwing function of type '(Error) throws -> Supplier' to non-throwing function type '(Error) -> Guarantee'

Why does it try to convert? It seems to me, it has to use this func:

public func recover(on: DispatchQueue? = default, policy: PromiseKit.CatchPolicy = default, _ body: @escaping (Error) throws -> U) -> PromiseKit.Promise where U : Thenable, Self.T == U.T

from PromiseKit

I added explicit types and divided promise into blocks to not miss something


Solution

  • You should return Promise to chain correctly, like this :

    self.supplierController
        .update(supplier: supplier)
        .recover { error -> Promise<Supplier> in
            let supplier: Supplier = supplier
            guard (error as NSError).code == 405 else {
                throw error
            }
    
            return .value(supplier)
        }
        .done { (_: Supplier) in
            changeCompanyIdAndAppendMessage()
        }
    

    source: https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md