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 - Swift - 方法链

regex - Swift 3 replacingOccurrences 正则表达式

swift - ReactiveCocoa 对成员 RACSignal 的引用不明确

javascript - Node.js Express-Session + Redis 单实例问题

javascript - Promise.all 然后 (js)

ios - 如何在 TableView Controller 中放置文本字段以读取内容

ios - 使用 iOS 一次获取多个网页的大小

ios - 刚好输入一个数字后移至下一个 UITextField

javascript - 如何使用 Recast.ai 使用 message.addReply 添加来自基于 promise 的 API 调用的结果?

ios - 如何处理 Storyboard中的长 View