【问题标题】:Using PromiseKit I want to make multiple API calls使用 PromiseKit 我想进行多个 API 调用
【发布时间】:2023-04-10 08:56:02
【问题描述】:

我在我的项目中使用 PromiseKit,我需要对 API 进行批量/多次调用并等待所有响应。任何想法如何做到这一点?我对 PromiseKit 很陌生,在他们的 Github 上没有找到任何关于此的内容(可能没有看到或理解它)

我目前正在尝试但失败的是:

    let ids = [1, 2, 3, 4, 5]
    firstly {

               getURLPathsFor(ids) // maybe I'm doing this wrong - this returns a Promise<[String]>

            }.thenMap { url in

                ApiManager.shared.request(url, method: .delete)

            }.done { _ in
                seal.fulfill(())
            }.catch { error in
                seal.reject(error)
            }

    func getURLPathsFor(_ ids: [UInt]) -> Promise<[String]> {
        let path = "/somePath"
        var URLs = [String]()
        return Promise { seal in
            ids.forEach { uid in
                AppConfigManager.shared.getApiUrl(path: path, uid).done { url in
                    URLs.append(url)
                    seal.fulfill(URLs)
                }.catch { error in
                    seal.reject(error)
                }
            }
        }
    }

任何帮助都会很棒,真的坚持这个。

【问题讨论】:

    标签: ios swift promisekit


    【解决方案1】:

    所以我设法使用 PromiseKit 实现了我想要的批量调用并一起处理所有错误:

    private func batchDeleteItem(with itemId: UInt) -> Promise<(UInt, AppError?)> {
        return Promise { seal in
            firstly {
                AppConfigManager.shared.getApiUrl(path: Constants.Api.deleteItemRequestPath, itemId)
            }.then { url in
                ApiManager.shared.request(url, method: .delete)
            }.done { _ in
                seal.fulfill((itemId, nil))
            }.catch { error in
                guard let appError = error as? AppError else {
                    seal.reject(error)
                    return
                }
                seal.fulfill((itemId, appError))
            }
        }
    }
    

    我在地图中调用此方法,并且为了收集无法删除的项目的 ID,我将 catch 与fulfill 一起处理 - 仅拒绝服务器端错误(这是我的案例所需要的) :

    return Promise { seal in
    
            let promises = ids.map { itemId in
                batchDeleteNode(with: itemId)
            }
    
            when(fulfilled: promises).done { results in
                seal.fulfill(results)
            }.catch { error in
                seal.reject(error)
    
            }
        }
    

    为了将所有错误分组并等待我使用when(fulfilled: promises).done {...}

    我并不是说它是完美的,但似乎工作得很好,而且我在这个过程中学到了很多关于 PromiseKit 的知识。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      相关资源
      最近更新 更多