所以我在过去的几天里一直在玩承诺,只是试图转换一些项目,使用承诺,但我不止一次遇到这个问题。
在阅读文章和教程时,一切看起来都很顺利和干净:
getDataFromDB()
.then(makeCalculatons)
.then(getDataFromDB)
.then(serveToClient)
但实际上,事实并非如此。
程序有很多改变整个流程的“if 条件”:
getDataFromCache(data).then(function(result){
if(result){
return result;
}else{
return getDataFromDB();
}
}).then(function(result){
if(result){
serveToClient() //this does not return a promise, so undefined returned...
}else{
return getDataFromWebService(); //this does return a promise,
}
}).then(function(result){
//i dont want to reach here if i already serveToClient()...
//so i basically have to check "if(result)" for all next thens
if(result){
//do more stuff
}
}).then(...
我有两个主要问题:
- 我发现自己添加了很多
if
的条件then
回调。
- 我还在进入下一个
then
回调,即使我已经完成了(serveToClient
)
我遵循正确的模式吗?
你无法避免if
语句,因为这是您的逻辑流程所必需的。你不得不branch如果您不想在某一部分继续承诺链,则您的控制流if
。所以如果在你第二个的某个时候.then()
处理程序,你不想继续第三个.then()
处理程序,那么您需要像这样分支逻辑并放置后续的.then()
2号内的处理程序.then()
处理程序在自己的逻辑分支中。
你不能只继续顶级分支,因为这是中止未来的唯一方法.then()
主链中的逻辑是拒绝承诺(您可能不想这样做)或添加另一个承诺if
检查每个.then()
处理程序来决定是否应该跳过它(恶心)。
因此,您可以像这样分支逻辑:
getDataFromCache().then(function(result){
if(!result) {
return getDataFromDB()
} else {
return result;
}
}).then(function(result){
// branch promise chain here into two separate branches
if(result){
// do not continue the promise chain here
// call a synchronous operation
serveToClient();
} else {
// continue promise chain here
return getDataFromWebService().then(function(result) {
if(result){
//do more stuff
}
}).then(...); // you can continue the promise chain here
}
}).catch(function(err) {
// process any errors here
});
您可能会发现这些其他答案很有用:
理解 javascript 的承诺;堆栈和链接 https://stackoverflow.com/questions/29853578/understanding-javascript-promises-stacks-and-chaining/29854205#29854205
Promise.then.then 和 Promise.then; 之间有区别吗?承诺.然后 https://stackoverflow.com/questions/32216619/is-there-a-difference-between-promise-then-then-vs-promise-then-promise-then/32216660#32216660
仅供参考,您可以将上面的代码重新组织得更简洁,如下所示:
getDataFromCache().then(function(result) {
if (result)
serveToClient();
} else {
return getDataFromWebService().then(function(result) {
if(result){
//do more stuff
}
}).then(...); // you can continue the promise chain here
}
}).catch(function(err) {
// process any errors here
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)