1

Given the following methods:

func loadFromCache(url: URL) -> Promise<Array<StockItem>>
func loadFromNetwork(url: URL) -> Promise<Array<StockItem>>

I have implemented a method that returns a new promise, by trying the cache first, then the network as follows

func load(skip: Int, query: String?, onlyInStock: Bool = false) -> Promise<Array<StockItem>> {

    let url = self.urlFor(skip: skip, query: query, onlyInStock: onlyInStock)
    print("Loading: \(url)")

    return Promise { fulfill, reject in
        self.loadFromCache(url: url).then { (items) in
            return fulfill(items)
        }.catch { (error) in
            self.loadFromNetwork(url: url).then { (items) in
                fulfill(items)
            }.catch { (error) in
                reject(error)
            }
        }
    }
}

I think there must be a better way to write the method above. How can I write it as a proper promise chain, without the nested closures?

In other words, how can I compose two promises into one?

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185

1 Answers1

3

What you are looking for is the recover operator.

func load(skip: Int, query: String?, onlyInStock: Bool = false) -> Promise<[StockItem]> {
    let url = urlFor(skip: skip, query: query, onlyInStock: onlyInStock)
    return loadFromCache(url: url).recover { _ in
        return loadFromNetwork(url: url)
    }
}
Daniel T.
  • 32,821
  • 6
  • 50
  • 72