PromiseKit 6 iOS 链接

问题描述

我正在尝试链接一些 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 语法什么的。

有什么想法吗?

解决方法

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

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

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)
}

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