Caching typically translates into an instant performance win in most applications. In this post I will demonstrate how to add basic cache handling to promise based http calls.

The following example is using Angular and its $q based promise implementation, but the technique applies to promises in general.

Many developers prefer to cache some resolved data value from a promise, but in this example I want to instead cache the promise instance itself. The code listing below shows a sample controller with a call to an article service that sits on top of $http.

Controller

angular.module('blog').controller('demoController', ['articleService','$scope', function(articleService, $scope){ $scope.getTopArticles = function(){ articleService.getTopArticles().then(function(response){ $scope.articles = response.data; }); }; }]);

ArticleService

angular.module('blog').factory('articleService', [ '$http', function($http){ var topArticlesCached; function getTopArticles(){ if(!topArticlesCached){ topArticlesCached = $http.get('/toparticles'); } return topArticlesCached; } return {getTopArticles:getTopArticles}; }]);

As you can see, the promise variable serves as a cache for the promise returned by the articleService.

I find this setup to be ideal for Angular since services are singletons so you are guaranteed to only have one cached instance. This means that several callers can call the same service at the same time without having to wait for a resolved data value to be cached. After the promise resolves the cached instance and its data will continue to be available to all subsequent calls.