title: Caching a promise object in AngularJS service
body: <p>I want to implement a dynamic loading of a static resource in AngularJS using Promises. The problem: I have couple components on page which might (or not, depends which are displayed, thus dynamic) need to get a static resource from the server. Once loaded, it can be cached for the whole application life.</p>
  
  <p>I have implemented this mechanism, but I'm new to Angular and Promises, and I want to make sure if this is a right solution \ approach.</p>
  
  <pre><code>var data = null;
  var deferredLoadData = null;
  
  function loadDataPromise() {
    if (deferredLoadData !== null)
      return deferredLoadData.promise;
  
    deferredLoadData = $q.defer();
  
    $http.get("data.json").then(function (res) {
      data = res.data;
      return deferredLoadData.resolve();
    }, function (res) {
      return deferredLoadData.reject();
    });
  
    return deferredLoadData.promise;
  }
  </code></pre>
  
  <p>So, only one request is made, and all next calls to loadDataPromise() get back the first made promise. It seems to work for request that in the progress or one that already finished some time ago.</p>
  
  <p>But is it a good solution to cache Promises?</p>