我正在尝试API请求,但是收到错误
Cannot assign value of type 'Promise<T>' to type 'Promise<_>?'
我不知道“承诺<_>在哪里?”出现。
下面是代码:在as处抛出错误!承诺'
class Cache<T> {
private let defaultMaxCacheAge: TimeInterval
private let defaultMinCacheAge: TimeInterval
private let endpoint: () -> Promise<T>
private let cached = CachedValue<T>()
private var pending: Promise<T>?
// Always makes API request, without regard to cache
func fresh() -> Promise<T> {
// Limit identical API requests to one at a time
if pending == nil {
pending = endpoint().then { freshValue in
self.cached.value = freshValue
return .value(freshValue)
}.ensure {
self.pending = nil
} as! Promise<T>
}
return pending!
}
//...More code...
}
和缓存的初始化
init(defaultMaxCacheAge: TimeInterval = .OneHour, defaultMinCacheAge: TimeInterval = .OneMinute, endpoint: @escaping () -> Promise<T>) {
self.endpoint = endpoint
self.defaultMaxCacheAge = defaultMaxCacheAge
self.defaultMinCacheAge = defaultMinCacheAge
}
和CachedValue
class CachedValue<T> {
var date = NSDate.distantPast
var value: T? { didSet { date = NSDate() as Date } }
}
答案 0 :(得分:1)
您似乎对在PromiseKit(migration guide to PMK6)中使用then
/ map
感到困惑:
then
被馈入先前的承诺值,并要求您返回承诺。
map
被送入先前的承诺值,并且要求您返回非承诺,即。一个值。
因此,您应该将then
更改为map
以返回T
,而不是Promise<T>
结束:
pending = endpoint()
.map { freshValue in
self.cached.value = freshValue
return freshValue
}.ensure {
self.pending = nil
}