How to maintain a promise-like API in this case?

后端 未结 2 1962
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 05:54
function foo(options) {
  if(!isValid(options)) {
    // I want to return a resolved promise here to permit client code to continue without a failure
  }

  return p         


        
相关标签:
2条回答
  • 2020-12-12 06:22

    Native Promises

    Take a look at the native Promise object's static methods resolve and reject.

    function foo(options) {
      if(!isValid(options)) {
        return Promise.resolve();
      }
    
      return promisifiedThirdPartyApi(options);
    }
    

    Angular $q

    Use $q.when to return a resolved Promise from some non-Promise object:

    function foo(options) {
      if(!isValid(options)) {
        return $q.when([]);
      }
    
      return promisifiedThirdPartyApi(options);
    }
    

    Q Promises

    Use Q.resolve() which returns a resolved promise.

    function foo(options) {
      if(!isValid(options)) {
        return Q.resolve();
      }
    
      return promisifiedThirdPartyApi(options);
    }
    
    0 讨论(0)
  • 2020-12-12 06:27
    function foo(options) {
      return new Promise(function(accept, reject) {
         if(!isValid(options)) {
             reject();
          }
    
         promisifiedThirdPartyApi(options).then(function() {
            accept();
         });
       });
    }
    

    Note that Q might have some shortcuts for this...

    0 讨论(0)
提交回复
热议问题