PromiseKit 6
我有一个从数据库中获取警报列表的函数,然后我需要在每个数据库上使用contentId属性来获取内容并将其附加到适当的警报项。
也许有更好的方法,但是现在,我想到的是将诺言收集到列表中并调用when(resolved :)。我之所以选择它,是因为如果任何承诺失败了,我希望能够退还所有可以通过的承诺。
在函数attachContents中的then处理程序中,该处理程序通过此类型[Result]传递,但映射列表时我只能访问的字段是isFulfilled 我检查了Result是什么类型,发现了这个:
public enum Result<T> {
case fulfilled(T)
case rejected(Error)
}
public extension PromiseKit.Result {
var isFulfilled: Bool {
switch self {
case .fulfilled:
return true
case .rejected:
return false
}
}
}
它导致我进入Resolver.swift中的第一个,所以我不确定为什么我无法通过调用fulfilled来获取数据
private func getContent(for alert: Model) -> Promise<ViewModel> {
return firstly { () -> Promise<Any> in
if let contentType = AlertContentType(rawValue: alert.type) {
switch contentType {
case .news:
return newsService.get(contentId: contentId, superareaId: superareaId).compactMap { $0 as Any }
case .insight:
return insightService.get(contentId: contentId, superareaId: superareaId).compactMap { $0 as Any }
}
} else { throw DataError.Missing(error: "Could not retrieve type!") }
}.compactMap { content in
var viewModel = alert.toViewModel()
viewModel.content = content
return viewModel
}
}
private func attachContents(to alerts: [Model]) -> Promise<[ViewModel]> {
return firstly { () -> Guarantee<[Result<ViewModel>]> in
let contentPromises: [Promise<AlertViewModel>] = alerts.map {
return self.getContent(for: $0)
}
return when(resolved: contentPromises)
}.then { (vModels: [Result<ViewModel>]) -> Promise<[OIAlertViewModel]> in
vModels.map { (vm: Result<OIAlertViewModel>) in
// vm.isFulfilled is the only accessible property here
// can't call
}
}
}
答案 0 :(得分:1)
Result
是.fulfilled
或.rejected
vModels.map { (vm: Result<OIAlertViewModel>) in
switch vm {
case .fulfilled(let alert):
print(alert)
case .rejected(let error):
print(error)
}
}