Potentially async function return a promise that immediately resolves?

匿名 (未验证) 提交于 2019-12-03 02:01:02

问题:

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!    }); } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!