0

I'm attempting an API Request, however I'm receiving an error

Cannot assign value of type 'Promise<T>' to type 'Promise<_>?'

I have no idea where 'Promise<_>?' is arising.

Here's a look at the code: throwing error at 'as! Promise'

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...
}

And Cache's init

init(defaultMaxCacheAge: TimeInterval = .OneHour, defaultMinCacheAge: TimeInterval = .OneMinute, endpoint: @escaping () -> Promise<T>) {
    self.endpoint = endpoint
    self.defaultMaxCacheAge = defaultMaxCacheAge
    self.defaultMinCacheAge = defaultMinCacheAge
}

And CachedValue

class CachedValue<T> {
    var date = NSDate.distantPast
    var value: T? { didSet { date = NSDate() as Date } }
}
Konrad Wright
  • 1,254
  • 11
  • 24

1 Answers1

1

Looks like you're confused about using then/map in PromiseKit (migration guide to PMK6):

then is fed the previous promise value and requires you return a promise.
map is fed the previous promise value and requires you return a non-promise, ie. a value.

So, you should change then to map to return the T, not Promise<T> in closure:

pending = endpoint()
    .map { freshValue in
        self.cached.value = freshValue
        return freshValue
    }.ensure {
        self.pending = nil
    }
pacification
  • 5,838
  • 4
  • 29
  • 51