I have developed a rather intricate method for retrieving resources using $http.
This method returns a promise and first checks my local cache to see if the resources are already available. If they are, it will return the cached data; if not, it will make the $http request. This works well once the resource has been cached, but I have several functions in the application that call this method on load, and each one of them ends up making the http request because the resources have not been returned and cached yet.
I devised a simple check to address this issue, but I can't help but think there might be a more efficient solution. I introduced a boolean variable that is set to true while the method is in the process of fetching the resource. If it is, I resolve the method with a timeout of half a second to allow the request to complete. The code snippet is provided below.
So, is there a better approach?
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 && !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);
});
}
});
}