0

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
    });
}
user1491636
  • 2,355
  • 11
  • 44
  • 71

1 Answers1

0

Yes - it should always return a promise unless there is another consideration preventing it from doing so. This is for consistency - if a method might be asynchronous it is best practice to always treat it as asynchronous so you won't get funky race conditions later on.

Since you can't block anyway, and the workarounds are hacky - I think it probably fits your problem optimally anyway. Simply put all reliant code in a then.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504