Alamofire嵌套请求

编程入门 行业动态 更新时间:2024-10-26 10:31:20
本文介绍了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嵌套请求

本文发布于:2023-11-26 03:25:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632444.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   Alamofire

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!