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?