javascriptangularjshttpcachefactory

Async $cacheFactory with $http and $resource


I am attempting to implement an async cache on top of $resource using $cacheFactory.

Poking around in the $http source it appears to support returning promises from the cache. I would assume that after that I could simply resolve the promise with cache data or reject it and let $http do its thing, which then would put data back in the cache. Problem is.. I just doesn't work. Does $http ACTUALLY support promises?

https://github.com/angular/angular.js/blob/master/src/ng/http.js#L895

  if (cache) {
    cachedResp = cache.get(url);
    if (isDefined(cachedResp)) {
      if (isPromiseLike(cachedResp)) {
        // cached request has already been sent, but there is no response yet
        cachedResp.then(removePendingReq, removePendingReq);
        return cachedResp;
      } else {
        // serving from cache
        if (isArray(cachedResp)) {
          resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
        } else {
          resolvePromise(cachedResp, 200, {}, 'OK');
        }
      }
    } else {
      // put the promise for the non-transformed response into cache as a placeholder
      cache.put(url, promise);
    }
  }

This is were $http handles the caching, as you can see it does actually check if a promise is returning (Line #898). But it appears that both resolving or reject simply clears the request from the pending queue. How do I actually send the data or single $http to continue the request?

Here is a Plunker of about what I'm trying to accomplish.

http://plnkr.co/edit/TwXumrAunG9b5JKo5OlB?p=preview


Solution

  • There is a bug in AngularJS. When resolving (or rejecting) a promised return from the cache $http does not handle the data in any way.

    Related Bug https://github.com/angular/angular.js/pull/6534