这就是我使用 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
被拆分为 then
、done
和 map
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 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
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/