【问题标题】:PromiseKit 6 iOS chainingPromiseKit 6 iOS 链接
【发布时间】:2021-05-12 05:46:33
【问题描述】:

我正在尝试链接一些 API 调用,但我认为我混淆了一些概念。希望得到一些说明和代码示例。

我已经实现了这些功能……

func promiseFetchPayments(for accountId: String) -> Promise <[OperationResponse]> {
        return Promise <[OperationResponse]> { seal in
            
            payments(for: accountId) { (records, error) in
                
                if let recs = records {
                    seal.resolve(.fulfilled(recs))
                    return
                }
                
                if let e = error {
                    seal.reject(e)
                    return
                }
            }
        }
    }

func payments(for accountId: String, completion: @escaping (_ records: [OperationResponse]?, _ error: Error?) -> Void) {
        stellar.payments.getPayments(
            forAccount: accountId,
            order: Order.descending,
            limit: 10
        ) { response in
            switch response {
            case .success(let paymentsResponse):
                
                DispatchQueue.main.async {
                    completion(paymentsResponse.records, nil)
                }

            case .failure(let error):
                DispatchQueue.main.async {
                    completion(nil, error)
                }
            }
        }
    }

我正在尝试这样使用它:

firstly {
            promiseFetchPayments(for: "XXX")
        }.done { records in
            print(records)
        } .catch { error in
            print(error)
        }

现在这实际上 ^^^ 工作正常!!!!我的问题是我希望能够将 done 更改为 then 并能够链接另一个函数/响应或更多。

但我不断收到的错误是:

不能符合 Thenable。

我正在寻找与此非常相似的东西(我知道语法不正确,只是在逻辑上遵循链......

firstly {
            stellar.promiseFetchPayments(for: "")
        }.done { records in
            print(records)
        }.then {
            // call some other method 
        }.done { data in 
          // more data 
        }.catch { error in
            print(error)
        }

这真的可能吗?似乎无法在互联网上获得任何教程来编译。看来 Swift 编译器真的不喜欢 PMK 语法什么的。

有什么想法吗?

【问题讨论】:

  • 如果您在 iOS 13 之后不能向后兼容,可能需要考虑切换到 Combine。
  • @matt 我正试图用结合来做到这一点。但是我发现它很难使用并且超级不直观。真的也不适应语法,很难理解。我将开始阅读您的网站apeth.com/UnderstandingCombine/toc.html,看看它可能会教给我更好的东西。
  • 如果有帮助请告诉我!它意味着作为一种教学工具。另请注意,我在这里多次解释了如何链接异步调用。见特别。 stackoverflow.com/questions/59428026/…
  • @matt 会的,谢谢!

标签: ios promisekit


【解决方案1】:

问题是因为您正在链接done,这不喜欢您尝试调用then

相反,您需要保存 Promise 并将其用于以后的调用。你可以这样做:

let promise = firstly {
    stellar.promiseFetchPayments(for: "")
}

promise.done { records in
    print(records)
}

promise.then {
    // call some other method 
}.done { data in 
    // more data 
}.catch { error in
    print(error)
}

您甚至可以从一个方法返回该承诺以在其他地方使用,或将其传递给另一个方法。

【讨论】:

  • 啊,太棒了。谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-09-11
  • 2015-12-14
  • 2023-03-29
  • 2018-08-15
  • 2012-11-01
  • 2016-02-08
  • 2018-11-03
  • 1970-01-01
相关资源
最近更新 更多