swiftasynchronouspromisekit

How can I use PromiseKit w/ Race to return the quickest result


I have a network request. I'd like to make this request and fallback to a cached value if

I was thinking I could use race to make the request and also use after to give myself a sort of time out on the promise.

Something like -

  func getCompany() -> Promise<Company> {

    let request: Promise<Company> = client.request(.getCompany)
    let cachedResponse: Promise<Company?> = cache.getObject(ofType: Company.self, forKey: "company")

    return race(request, after(seconds: 4).then(cachedResponse))
  }

This fails to compile however with

Cannot convert value of type 'Promise<Company?>' to expected argument type '(Void) -> Guarantee<_>'

I'd like to say essentially return the first one that resolves, which in this case would be cachedResponse if request took longer than 4 seconds.


Solution

  • There's a couple of things you will need to do first. It looks like one of your requests return an optional, you will need to handle this in some way as race is going to require all promises to conform to the same type.

    If you are planning on using this approach elsewhere, I would suggest creating a simple util to wrap around the delayed response.

    func await<T>(for delay: TimeInterval, then body: Promise<T>) -> Promise<T> {
      return after(seconds: delay).then { _ in body }
    }
    
    

    You can then refactor your getCompany method to race your requests as:

      func getCompany() -> Promise<Company?> {
        let request: Promise<Company?> = client.request(.getCompany)
        let cachedResponse: Promise<Company?> = await(for: 2, then: cache.getObject(ofType: Company.self, forKey: "company"))
    
        return race(request, cachedResponse)
      }