我需要对同一API发出三个不同的请求。这些调用都不依赖于另一个。我目前的请求嵌套方式如下:
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() } } } } } } }我觉得这可能不可行od方法,并且正在寻找一些指导,以寻求更好的解决方案。当前,生成的数组似乎正确填充了我的表视图,但是我忍不住觉得这种嵌套方法不正确。
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.
推荐答案如果您的任何操作都不依赖,那么为什么要嵌套它们?我发现您要等到第三个完成后才能重新加载UITableView-如果这很困难,则它们 是依赖的。
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.
当它们相互依赖时,这种嵌套有时称为厄运金字塔。清理它的一种好方法是将嵌套代码包装为monad,这将允许以下操作:
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:
- 代码可以整齐地链接,而不是嵌套,从而提高了可读性。
- 您可以使用单个错误处理,而不是重复进行的错误处理
- 任何最终/始终执行的任务都可以表达得很整洁。
这被称为承诺。这是一个很棒的关于它们如何工作的教程。
This is called a Promise. Here's an excellent tutorial on how they work.
还有一些很棒的库。 PromiseKit 是一种流行的方法。
And there's some great libraries. PromiseKit is a popular one.
更多推荐
Alamofire嵌套请求
发布评论