ios - 在 PromiseKit 6 中返回 void

标签 ios swift promise promisekit

这就是我使用 PromiseKit 4.5 的结果

api.getUserFirstName().then { name -> Void in
  print(name)
}

getUserFirstName()返回 Promsise<String> .我更新到 PromiseKit 6,现在会抛出一个错误: Cannot convert value of type '(_) -> Void' to expected argument type '(_) -> _'

这条错误消息对我来说意义不大。我该如何解决这个问题?

编辑:所以这似乎解决了这个问题,但我对发生的事情知之甚少:

api.getUserFirstName().compactMap { name in
  print(name)
}

现在 then() 之间有什么区别?和 compactMap()

最佳答案

符合PromiseKit 6.0 Guide then 被拆分为 thendonemap

  • then 被输入之前的 promise 值并要求您返回一个 promise。
  • done 被输入之前的 promise 值并返回一个 Void promise(这是链使用的 80%)
  • map 被提供了先前的 promise 值,并要求您返回一个非 promise 值,即。一个值。

为什么会这样?正如开发人员所说:

With PromiseKit our then did multiple things, and we relied on Swift to infer the correct then from context. However with multiple line thens it would fail to do this, and instead of telling you that the situation was ambiguous it would invent some other error. Often the dreaded cannot convert T to AnyPromise. We have a troubleshooting guide to combat this but I believe in tools that just work, and when you spend 4 years waiting for Swift to fix the issue and Swift doesn’t fix the issue, what do you do? We chose to find a solution at the higher level.

所以在你的情况下可能需要使用done

func stackOverflowExample() {
    self.getUserFirstName().done { name -> Void in
        print(name)
    }
}

func getUserFirstName() -> Promise<String> {
    return .value("My User")
}

compactMap 允许您在返回 nil 时进行错误传输。

firstly {
    URLSession.shared.dataTask(.promise, with: url)
}.compactMap {
    try JSONDecoder().decode(Foo.self, with: $0.data)
}.done {
    //…
}.catch {
    // though probably you should return without the `catch`
}

查看更多信息 release guide

compactMap 已重命名为 flatMap see discussions here

关于ios - 在 PromiseKit 6 中返回 void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49147115/

相关文章:

ios - 当 MKMap 在 iOS 中面向北方时指南针消失

regex - Swift中字符串中子字符串的出现次数

javascript - 什么是 promise 处理器模式?

javascript - jQuery .done 未按预期返回

ios - 更改 UIRefreshControl 的位置并触发事件

ios - 在应用程序中保存默认数据 ios swift 核心数据

iphone - Swift - 在 Swift 中使用#define

ios - 由于错误 "Failed to use existing instance 0 for app with bundle identifier: com.apple.Carousel",Apple Watch 应用无法构建

iphone - 制作应用 Urban Airship

javascript - 将 promise 链中的值传递给后续处理程序