Where asyncBananaRequest
returns a promise -
function potentiallyAsync () {
if (cachedBanana) {
return asyncBananaRequest();
}
return
While SomeKittens is awesome, his answer uses the deferred anti pattern.
I suggest the following:
function potentiallyAsync () {
return (cachedBanana) ? Promise.resolve(cachedBanana) : asyncBananaRequest();
}
potentiallyAsync().then(function(banana){
//use banana
});
In Angular's $q you'd use the exact same thing only with $q.when(cachedBanana)
instead of the ES6 standards Promise.resolve
.
This form of chaining and using .resolve (.when in $q) to create new promises are bread and butter of promises. Deferred objects should only be used at absolute endpoints when promisifying callback based APIs.
Sure! Use a pattern along these lines:
function bananas($q) {
var def = $q.defer();
if (cachedBananas) {
def.resolve(cachedBananas);
} else {
asyncBananas('Monkey.co')
.success(function(bananas) {
def.resolve(bananas);
});
}
return def.promise;
}
Meanwhile:
function monkey(bananas) {
bananas.then(function(bananas) {
bananas.eat(); // Yum!
});
}