Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

javascript - Potentially async function return a promise that immediately resolves?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...