问题
I need to make three different requests to the same API. None of these calls are dependent on the other. I currently have my requests nested like so:
API.getPopularMovies() { responseObject, error in
if let results = responseObject {
self.popularMovies = results
self.API.getNowPlayingMovies() { responseObject, error in
if let results = responseObject {
self.nowPlayingMovies = results
self.API.getUpcomingMovies() { responseObject, error in
if let results = responseObject {
self.upcomingMovies = results
self.movies = [self.popularMovies, self.nowPlayingMovies, self.upcomingMovies]
self.tableView.reloadData()
}
}
}
}
}
}
}
I feel like this may not be a good approach, and am looking for some guidance towards a better way of going about this. Currently, the resulting arrays seem to properly populate my table view, but I can't help but feel like this nested approach is incorrect.
回答1:
If none of your operations are dependent, then why do you nest them? I see that you don't reload your UITableView until the third one completes - if that's a hard requirement, then they are dependent.
When they are dependent, this kind of nesting is sometimes called a 'Pyramid of Doom'. A great way to clean it up is to wrap the nested code as a monad, which would allow the following:
- Code can be chained neatly, rather than nested, improving readability.
- You can use single rather than repeated error handling
- Any final/always tasks can be expressed neatly.
This is called a Promise. Here's an excellent tutorial on how they work.
And there's some great libraries. PromiseKit is a popular one.
来源:https://stackoverflow.com/questions/44092027/alamofire-nested-requests