需要帮助弄清楚如何写有条件的承诺
Need help figuring out how to write promise with conditional
这就是我想要做的
isAuthorized(params){
return new Promise(function(resolve, reject) {
if(params.property){
doSomething().then(function(e){
if(e){
resolve(true);
} else {
reject(false);
}
} else {
doSomethingElse().then(function(e){
if(e){
resolve(true);
} else {
reject(false);
}
}
}
但我收到警告:"a promise was created at handler but was not returned from" 而函数按预期运行。
我也试过了
isAuthorized(params){
if(params.property){
return new Promise(function(resolve, reject) {
doSomething().then(function(e){
if(e){
resolve(true);
} else {
reject(false);
}
});
} else {
return new Promise(function(resolve, reject) {
doSomethingElse().then(function(e){
if(e){
resolve(true);
} else {
reject(false);
}
});
}
}
如果您需要更多信息,请告诉我.. 谢谢 :)
这是在抱怨你没有在任何地方返回内在的 doSomething()
承诺。要避免 promise-callback anti-pattern,请尝试这样的操作:
function isAuthorized(params) {
function resolveIfTruthy(e) {
if (e) return Promise.resolve(true);
else return Promise.reject(false);
}
if (params.property) {
return doSomething()
.then(resolveIfTruthy);
} else {
return doSomethingElse()
.then(resolveIfTruthy);
}
}
这就是我想要做的
isAuthorized(params){
return new Promise(function(resolve, reject) {
if(params.property){
doSomething().then(function(e){
if(e){
resolve(true);
} else {
reject(false);
}
} else {
doSomethingElse().then(function(e){
if(e){
resolve(true);
} else {
reject(false);
}
}
}
但我收到警告:"a promise was created at handler but was not returned from" 而函数按预期运行。
我也试过了
isAuthorized(params){
if(params.property){
return new Promise(function(resolve, reject) {
doSomething().then(function(e){
if(e){
resolve(true);
} else {
reject(false);
}
});
} else {
return new Promise(function(resolve, reject) {
doSomethingElse().then(function(e){
if(e){
resolve(true);
} else {
reject(false);
}
});
}
}
如果您需要更多信息,请告诉我.. 谢谢 :)
这是在抱怨你没有在任何地方返回内在的 doSomething()
承诺。要避免 promise-callback anti-pattern,请尝试这样的操作:
function isAuthorized(params) {
function resolveIfTruthy(e) {
if (e) return Promise.resolve(true);
else return Promise.reject(false);
}
if (params.property) {
return doSomething()
.then(resolveIfTruthy);
} else {
return doSomethingElse()
.then(resolveIfTruthy);
}
}