Potentially async function return a promise that immediately resolves?

前端 未结 2 834
灰色年华
灰色年华 2020-12-18 12:54

Where asyncBananaRequest returns a promise -

function potentiallyAsync () {
  if (cachedBanana) {
    return asyncBananaRequest();
  }
  return         


        
相关标签:
2条回答
  • 2020-12-18 13:35

    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.

    0 讨论(0)
  • 2020-12-18 13:49

    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!
       });
    }
    
    0 讨论(0)
提交回复
热议问题