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

不问归期 提交于 2019-12-17 21:19:15

问题


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?


回答1:


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



回答2:


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...



来源:https://stackoverflow.com/questions/32521737/how-to-maintain-a-promise-like-api-in-this-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!