Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...