潜在的异步函数会返回一个立即解析的承诺吗? [英] Potentially async function return a promise that immediately resolves?
问题描述
其中 asyncBananaRequest
返回一个承诺 -
Where asyncBananaRequest
returns a promise -
function potentiallyAsync () {
if (cachedBanana) {
return asyncBananaRequest();
}
return ??cachedBanana??;
}
potentiallyAsync().then(function(banana){
//use banana
})
我想要一个香蕉,我可能已经将它缓存了。有没有办法让我在potentialAsync函数中返回缓存的香蕉作为一个立即用缓存的香蕉解决的承诺?
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?
我目前正在使用Q lib打包的Angular,但我希望有一个通用的实现
I'm currently using the Q lib packaged in Angular, but I'm hoping there's a generic implementation
推荐答案
虽然SomeKittens很棒,但他的答案使用延迟反模式。
While SomeKittens is awesome, his answer uses the deferred anti pattern.
我建议如下:
function potentiallyAsync () {
return (cachedBanana) ? Promise.resolve(cachedBanana) : asyncBananaRequest();
}
potentiallyAsync().then(function(banana){
//use banana
});
在Angular的$ q中,你只能使用 $完全相同的东西q.when(cachedBanana)
而不是ES6标准 Promise.resolve
。
In Angular's $q you'd use the exact same thing only with $q.when(cachedBanana)
instead of the ES6 standards Promise.resolve
.
这种形式的链接和使用.resolve(.when in $ q)来创造新的承诺是承诺的面包和黄油。在宣传基于回调的API时,只应在绝对端点使用延迟对象。
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.
这篇关于潜在的异步函数会返回一个立即解析的承诺吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!