简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM