可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Where asyncBananaRequest
returns a promise -
function potentiallyAsync () { if (cachedBanana) { return asyncBananaRequest(); } return ??cachedBanana??; } potentiallyAsync().then(function(banana){ //use banana })
I want a banana, I might already have it cached. Is there a way for me to return the cached banana in the potentiallyAsync functionas a promise that immediately resolves with the cached bananas?
I'm currently using the Q lib packaged in Angular, but I'm hoping there's a generic implementation
回答1:
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.
回答2:
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! }); }