title: Preventing multiple $http requests in Angular. Is there a better way?
body: <p>I've built a somewhat complex method for returning a resources via $http.</p>
  
  <p>The method returns a promise and then checks my local cache if the resources exists yet. If it does it will return the cached resources, if not it will make the $http request. This works great after the resource has been cached, but I have multiple functions through out the application that is hitting this method on load, and every one of them will make the http request because the resources hasn't been returned and cached yet.</p>
  
  <p>I came up with a simple check that fixes this, but I feel like there should be a better way. I added a boolean that is set to true if the method is in the middle of getting the resource, and if it is I resolve the method with a half second timeout, to give the request time to resolve. Code is below.</p>
  
  <p>So, is there a better way?</p>
  
  <pre><code>   var schools = [];
     var loadingSchools = false;
  
     function getAllSchools(forceUpdate) {
          return $q(function (resolve, reject) {
              if(loadingSchools) resolve($timeout(getAllSchools, 500));
  
              else{
  
                  loadingSchools = true;
  
                  if (schools.length &amp;&amp; !forceUpdate) {
                      loadingSchools = false;
                      resolve(schools);
                      return;
                  }
  
                  console.log('$http: Getting All Schools - schoolService.js');
  
                  $http.get(API_PATH + 'schools_GetAll', {cache:true})
                  .success(function(result) {
                      schools = result;
                      loadingSchools = false;
                      resolve(schools);
                  })
                  .error(function(error) {
                      schools = [];
                      loadingSchools = false;
                      reject(error);
                  });
              }
          });
      }
  </code></pre>