gpt4 book ai didi

swift - 无法返回末尾带有 catch block 的 promise 链

转载 作者:搜寻专家 更新时间:2023-10-31 08:28:12 26 4
gpt4 key购买 nike

这曾经有效,但对于 PromiseKit 版本 6 这...

func checkIn(request: CheckinRequest) -> Promise<CheckinResponse> {

let p = checkinService.checkIn(request: request)

.then { r -> Promise<CheckinResponse> in

return .value(r)

}.catch { e in


}

return p
}

... 给...

Cannot convert return expression of type 'PMKFinalizer' to return type 'Promise'

如何添加一个 catch block 并继续将链返回给调用函数?

最佳答案

你只需要删除 catch block ,如下所示,

func checkIn(request: CheckinRequest) -> Promise<CheckinResponse> {
let p = checkinService.checkIn(request: request)
.then { r -> Promise<CheckinResponse> in
return .value(r)
}
return p
}

在这里使用捕获 block 是无关紧要的,因为 error 应该由被调用者处理。


Guarantee 类是一个包装器 class 以进行可丢弃的 result 调用。所以我们可以创建一个方法来处理 promise,这样我们就可以使用 .done 回调来使用 result,如下所示,

extension Promise {

func result() -> Guarantee<T> {
return Guarantee<T>(resolver: { [weak self] (body) in
self?.done({ (result) in
body(result)
}).catch({ (error) in
print(error)
})
})
}
}

现在你可以简单地做,

let request = CheckinRequest()
checkinService.checkIn(request: request).result().done { response in
// Check in response
}

您仍然可以像下面那样对多个 promise 使用链接,

checkinService.checkIn(request: request).result().then { (result) -> Promise<Bool> in
// Use reuslt
return .value(true)
}.done { bool in
print(bool)
}.catch { (e) in
print(e)
}

关于swift - 无法返回末尾带有 catch block 的 promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53770491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com