Search code examples
swiftasynchronouspromisekit

PromiseKit fulfill and reject convention


I'm using PromiseKit to handle my network calls. I'm trying to see if there's a convention or a cleaner way to either fulfill or reject the promise early. As illustrated below, there are a few conditions that would require me to fulfill or reject early. I'm currently doing this by putting a return statement right afterward. I feel like this is rather clunky and am wondering if there's a better way to do this. Thanks!

return PromiseKit { fulfill, reject in
  if statusCode == 200 {
    if conditionA {
      if conditionB {
        fulfill(...)  // How do I stop the execution chain from here
        return
      } else {
        reject(...) // Or here, without having to call return every time 
        return
      }
    }
    reject(...)
  }
}

Solution

  • Rather than using fulfill and reject, you could return the Promise result. Below I have created a function showing you how it can be done:

    func someMethod(statusCode: Int, conditionA: Bool, conditionB: Bool) -> Promise<Any> {
        if statusCode == 200 {
            if conditionA {
                if conditionB {
                    return Promise(value: "Return value")
                } else {
                    return Promise(error: PromiseErrors.conditionBInvalid)
                }
            }
        }
        return Promise(error: PromiseErrors.invalidStatusCode)
    }
    
    enum PromiseErrors: Error {
        case invalidStatusCode
        case conditionBInvalid
    }
    

    By not using fullfill and reject, you can also clean up the code and move the conditionB check to a new function, such as:

    func someMethod(statusCode: Int, conditionA: Bool, conditionB: Bool) -> Promise<Any> {
        if statusCode == 200 {
            if conditionA {
                return conditionASuccess(conditionB: conditionB)
            }
        }
        return Promise(error: PromiseErrors.invalidStatusCode)
    }
    
        func conditionASuccess(conditionB: Bool) -> Promise<Any> {
        if conditionB {
            return Promise(value: "Return value")
        }
        return Promise(error: PromiseErrors.conditionBInvalid)
    }
    

    Are you using the PromiseKit extension for Foundation? It helps to simplify networking calls with Promises. You can get the extension here: https://github.com/PromiseKit/Foundation