swiftpromisekit

Can't return a promise chain with a catch block on the end


This used to work but with version 6 of PromiseKit this...

func checkIn(request: CheckinRequest) -> Promise<CheckinResponse> {
    let p = checkinService.checkIn(request: request)
        .then { r -> Promise<CheckinResponse> in
            return .value(r)
        }.catch { e in

        }
    return p
}

... gives ...

Cannot convert return expression of type 'PMKFinalizer' to return type 'Promise'

How can I add a catch block and continue to return the chain to the calling function?


Solution

  • You just need to remove the catch block as below,

    func checkIn(request: CheckinRequest) -> Promise<CheckinResponse> {
         let p = checkinService.checkIn(request: request)
              .then { r -> Promise<CheckinResponse> in
                  return .value(r)
            }
          return p
    }
    

    Using the catching block here is irrelevant as the error should be handled by the callee.


    Guarantee class is a wrapper class to make discardable result calls. So we can create a method that will process the promise so that we will just use the .done callback to use that result as below,

    extension Promise {
    
        func result() -> Guarantee<T> {
            return Guarantee<T>(resolver: { [weak self] (body) in
                self?.done({ (result) in
                    body(result)
                }).catch({ (error) in
                    print(error)
                })
            })
        }
    }
    

    Now you can simply do,

    let request = CheckinRequest()
    checkinService.checkIn(request: request).result().done { response in
        // Check in response
    }
    

    You can still use chaining for multiple promises as below,

    checkinService.checkIn(request: request).result().then { (result) -> Promise<Bool> in
            // Use reuslt
            return .value(true)
        }.done { bool in
            print(bool)
        }.catch { (e) in
            print(e)
    }