Promise chaining base on condition
zhouhao27 opened this issue · comments
In most case, there is only one error catch and chain for the successful operation. But for my case, what I want to do is if the operation success, then I'll return. If it's failed, I'll do another operation. Is it possible and how to express it in PromiseKit?
For example, how to convert this pseudo code to PromiseKit way?
fetchData1(fromURL: "someURL") { (response, results, error) in
switch response {
case .success:
if !data.isEmpty() {
// complete
} else {
fetchData2(for: results) { (response, results, error) in
switch response {
case .success:
// complete
}
case .fail:
// complete with error
}
}
case .fail:
fetchData2(for: results) { (response, results, error) in
switch response {
case .success:
// complete
}
case .fail:
// complete with error
}
}
}
This is a common pattern.
fetchData1
and fetchData2
should follow the general guidelines for creating promise-based APIs: they should be methods that return a promise that either yields a value or errors out. Let the caller handle dealing with the errors.
Something roughly like:
func fetchData1(fromURL: "someURL") -> Promise<MyData> {
return initialDataFetch(for: results)
.get { data in
if data.isEmpty() {
throw MyFetch.badInitialData
}
}.recover { fetchData2(for: results) }
}
Here, initialDataFetch
can be a separate method or just a firstly
block.