0
function foo(options) {
  if(!isValid(options)) {
    // I want to return a resolved promise here to permit client code to continue without a failure
  }

  return promisifiedThirdPartyApi(options); // Does not handle an invalid options object successfully
}

How can I idiomatically return a resolved promise in the "invalid" case?

Ben Aston
  • 49,455
  • 61
  • 188
  • 322
  • 1
    `return Q.defer().resolve().promise()` – Andrey Sep 11 '15 at 10:55
  • possible duplicate of [Is there a way to return early in deferred promise?](http://stackoverflow.com/q/31933675/1048572) or [JS Promises - if-else flow when only single path is async](http://stackoverflow.com/q/31559165/1048572) – Bergi Sep 12 '15 at 14:26

2 Answers2

2

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);
}
sdgluck
  • 21,802
  • 5
  • 67
  • 87
0
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...

Evert
  • 83,661
  • 18
  • 106
  • 170
  • Avoid the [promise constructor antipattern](http://stackoverflow.com/q/23803743/1048572) – Bergi Sep 12 '15 at 14:23