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
}
如何在"无效"中以惯用方式返回已解决的承诺?情况?
答案 0 :(得分:2)
查看本机Promise对象的静态方法resolve
和reject
。
function foo(options) {
if(!isValid(options)) {
return Promise.resolve();
}
return promisifiedThirdPartyApi(options);
}
使用$q.when
从某些非Promise对象返回已解析的Promise:
function foo(options) {
if(!isValid(options)) {
return $q.when([]);
}
return promisifiedThirdPartyApi(options);
}
使用Q.resolve()
返回已解决的承诺。
function foo(options) {
if(!isValid(options)) {
return Q.resolve();
}
return promisifiedThirdPartyApi(options);
}
答案 1 :(得分:0)
function foo(options) {
return new Promise(function(accept, reject) {
if(!isValid(options)) {
reject();
}
promisifiedThirdPartyApi(options).then(function() {
accept();
});
});
}
请注意,Q可能有一些快捷方式......