Check out myAngular article series with live demos and Facebook group Angular - Advanced Topics

Caching promises in Angular

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
Published: Sat Mar 14 2015

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.

If you liked this article, share it with your friends on social media:

We also have a new Facebook group about advanced Angular topics.

I invite you to follow me on twitter