Alamofire嵌套请求 [英] Alamofire Nested Requests

查看:93
本文介绍了Alamofire嵌套请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对同一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嵌套请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆