本文介绍了在PromiseKit 6中返回void的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我使用PromiseKit 4.5

This is what I had working with PromiseKit 4.5

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

getUserFirstName()返回 Promsise< String> 。我更新到PromiseKit 6,现在抛出一个错误:
无法转换类型'(_) - >的值Void'到预期的参数类型'(_) - > _'

getUserFirstName() returns a Promsise<String>. I updated to PromiseKit 6 and this now throws an error:Cannot convert value of type '(_) -> Void' to expected argument type '(_) -> _'

此错误消息对我来说没什么意义。我该如何解决这个问题?

This error message makes little sense to me. How do I fix this?

编辑:所以这似乎解决了这个问题,但我对此发生的事情几乎一无所知:

So this seems to fix it, but I have little understanding as to what's happening with this:

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

then() compactMap()?

What's the difference now between then() and compactMap()?

推荐答案

根据 然后被拆分为然后已完成地图


  • 然后被提供先前的承诺价值并要求您返回承诺。

  • 已完成被提供前一个承诺值并返回一个Void承诺(这是链使用量的80%)

  • map 被提供前一个承诺值,并要求您返回一个非承诺,即。一个值。

  • then is fed the previous promise value and requires you return a promise.
  • doneis fed the previous promise value and returns a Void promise (which is 80% of chain usage)
  • map is fed the previous promise value and requires you return a non-promise, ie. a value.

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

Why that was happend? As said developers:

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

So probably in your case needs to use done

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

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

compactMap 让你在返回nil时得到错误传输。

compactMap lets you get error transmission when nil is returned.

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

compactMap 已重命名为 flatMap

这篇关于在PromiseKit 6中返回void的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 17:13