I have an AngularJS function, that loads data from a webservice and then stores it in the localStorage. After calling this function the first time, the data should be loaded from localStorage (unless the cache is invalid after an hour).
I would like to externalize this function, but I'm scratching my head, how to put a sync and an async call into one method. Here we go.
function callWebService(url) {
var resultFromLocalStorage = localStorage.getItem(url);
if (resultFromLocalStorage && Utils.cacheIsStillValid()) { //(*)
$timeout(function() { buildTable(JSON.parse(resultFromLocalStorage)); }, 10);
} else {
$resource(url).get().$promise.then(function(result) {
localStorage.setItem("cacheExpiry", new Date().getTime() + Utils.ONE_HOUR_IN_MS);
localStorage.setItem(url, JSON.stringify(result));
buildTable(result);
});
}
}
//*Utils.cacheIsStillValid checks the localStorage item "cacheExpiry"
I would like to externalize that caching stuff, so in the end, I just want this:
function callWebService(url) {
var result = getResultFromCacheOrReload(url); // to be done
buildTable(result);
}
How can I do this? How would the method getResultFromCacheOrReload(url) look?
Thanks, Bernhard