jmdobry / angular-cache

angular-cache is a very useful replacement for the Angular 1 $cacheFactory.
http://jmdobry.github.io/angular-cache
MIT License
1.39k stars 156 forks source link

Data loaded in the onExpire function is only available at the next request #167

Closed ChristopherBrix closed 9 years ago

ChristopherBrix commented 9 years ago

When the cache is set to the passive deletion mode, onExpire is only called if the cached item is requested. But even if the onExpire code created a new entry for the current key, the get method always returns undefined. Only the next reload will work correctly (if the item didn't expire again).

Changing line 274 from value = undefined to value = this.get(key); did the trick for me, but it's not an optimal solution since it could create an infinite loop for very small maxAge values.

jmdobry commented 9 years ago

From the point of view of the user calling get(key) for an expired item in passive mode, the item is not in the cache, even if angular-cache is lazily removing the item from the cache at the time of the request. angular-cache cannot make any assumptions about what kind a code will be executed in onExpire. The user could very well be doing asynchronous things, such as retrieving fresh data from the server to put it back into the cache. get will return undefined if the item is expired. Changing this behavior would be a breaking change. Just before calling get(key), you can call touch(key) even if it is expired (assuming you're in passive mode), and the get call will return the item. You could create yourself a helper function to do this for you.

function touchGet(cacheOrCacheId, key) {
  if (typeof cacheOrCacheId === 'string') {
    CacheFactory.get(cacheOrCacheId).touch(key);
    return CacheFactory.get(cacheOrCacheId).get(key);
  } else {
    cacheOrCacheId.touch(key);
    return cacheOrCacheId.get(key);
  }
}
jmdobry commented 9 years ago

Maybe revisit this for 5.0


Closing because I’m not sure this is an issue, if you are convinced that this is really a bug, please feel free to re-open the issue and add more information:

Otherwise support is done via the mailing list.