Alamofire Nested Requests

两盒软妹~` 提交于 2019-12-24 02:59:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!