I need a function which will return a boolean value. The first time this function is called, it should load the value from an async service (that returns a promise) and then cache it. Subsequent calls to this function should return the cached value. Problem is the caller of this function should be blocked until it gets a value. Whats the best solution in this case? Should the function return a promise either way (i.e whether its cached or not), and just put everything that needs to be blocked inside promise.then(). And if thats a good solution, how do I return a promise in either case (e.g. when its cached or not)?
Below is some code to better illustrate the problem:
function isSomethingStored() {
if(getFromBrowserStorage() != null) {
var deferred = $q.defer();
deferred.resolve(true);
return deferred.promise;
}
var promise = ThirdParty.getSomethingThroughAjax();
promise.then(function(theSomething) {
addToBrowserStorage(theSomething);
return true;
});
return promise;
}
function caller() {
var promise = isSomethingStored();
promise.then(function(isReady) {
//we can continue
});
}