考虑以下方法:
func loadFromCache(url: URL) -> Promise<Array<StockItem>>
func loadFromNetwork(url: URL) -> Promise<Array<StockItem>>
我已经实现了一个返回新promise的方法,首先尝试缓存,然后按如下方式尝试网络
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)
}
}
}
}
我认为必须有更好的方法来编写上述方法。如何在没有嵌套闭包的情况下将其编写为正确的promise链?
换句话说,我如何将两个承诺合二为一?
答案 0 :(得分:2)
您正在寻找的是recover
运营商。
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)
}
}