在PromiseKit 6中返回void [英] Returning void in PromiseKit 6
问题描述
这就是我使用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()<之间有什么区别? / code>?
What's the difference now between then()
and compactMap()
?
推荐答案
根据 PromiseKit 6.0指南 然后
被拆分为然后
,已完成
和地图
-
然后
被提供先前的承诺价值并要求您返回承诺。 -
已完成
被提供前一个承诺值并返回一个Void承诺(这是链使用量的80%) -
map
被提供前一个承诺值,并要求您返回一个非承诺,即。一个值。
then
is fed the previous promise value and requires you return a promise.done
is 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:
使用PromiseKit我们的
然后
做了多件事,我们依赖在Swift上从上下文推断出正确的然后
。但是多行然后
s它将无法执行此操作,而不是告诉您情况不明确,它会发明一些其他错误。通常可怕的无法将T转换为AnyPromise
。我们有一个故障排除指南来解决这个问题,但我相信只有工作的工具,当你花了4年时间等待Swift解决问题而Swift没有解决问题时,你会怎么做?我们选择在更高级别找到解决方案。
With PromiseKit our
then
did multiple things, and we relied on Swift to infer the correctthen
from context. However with multiple linethen
s it would fail to do this, and instead of telling you that the situation was ambiguous it would invent some other error. Often the dreadedcannot 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
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!