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

Feature request : Promise API for get/put/remove #123

Closed rvenugopal closed 9 years ago

rvenugopal commented 10 years ago

Hullo

Thanks for creating this wonderful library.

Would it be possible to create a promise API for the accessor calls? I wrap most of my API calls inside services (which return promises since $http returns a promise). So there is some friction as your library does not return a promise. Please let me know if there is a way around this. I was hoping for something along the lines of what I posted down below.

Thanks -Rv


/*** Sample implementation suggestion ***/
function serviceFn(url, cacheKey) {

/// Return data from cache if available
/// Return data from server

profileCache.find(cacheKey)
     .then(function(data) {
            return data.result;
      }.then(function(data) {
            if (typeof(data) == 'undefined' {
                 /// Make http call here and then return the appropriate promise
            }

      } 

}
jmdobry commented 10 years ago

The current API is locked as being synchronous because it must maintain compatibility with $cacheFactory. Because angular-cache is completely synchronous, any new Promise-based API would simply be sugar for the following:

(angular-cache 3.x used in the example)

angular.module('myApp')
  .factory('PromiseCache', ['$q', function ($q) {
    var myCache = DSCacheFactory('myCache', {...});
    var methodsToWrap = ['get', 'put', 'remove' /* , etc. */];
    var promiseCache = {};

    angular.forEach(methodsToWrap, function (method) {
      promiseCache[method] = function () {
        var deferred = $q.defer();
        try {
          deferred.resolve(myCache[method].apply(myCache, arguments));
        } catch (err) {
          deferred.reject(err);
        }
        return deferred.promise();
      }
    });

    return promiseCache;
  }]);

You might be able to convince me to add something like this into angular-cache itself.

jmdobry commented 9 years ago

I'll just leave this here as an example of how to do it.