gpt4 book ai didi

javascript - 使用 Promises 的多路流的正确模式

转载 作者:数据小太阳 更新时间:2023-10-29 05:14:32 25 4
gpt4 key购买 nike

所以最近几天我一直在玩 promises,只是想转换一些项目,使用 promises,但是我遇到这个问题不止几次。

在阅读文章和教程时,一切看起来都很流畅和干净:

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

我有两个主要问题:

  1. 我发现自己在 then 回调中添加了很多 if 条件。
  2. 我仍在进入下一个 then 回调,即使我已经完成 (serveToClient)


我遵循的是正确的模式吗?

最佳答案

您无法避免 if 语句,因为这是您的逻辑流程所必需的。如果您不想在 if 的某一部分继续 promise 链,则必须分支您的控制流。因此,如果在第二个 .then() 处理程序的某些部分,您不想继续执行第三个 .then() 处理程序,那么您需要分支像这样的逻辑并将后续的 .then() 处理程序放在第二个 .then() 处理程序中它们自己的逻辑分支中。

你不能只继续顶级分支,因为在主链中中止 future .then() 逻辑的唯一方法是要么拒绝 promise (你可能不想要做)或添加另一个 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
});

您可能会发现这些其他答案很有用:

Understanding javascript promises; stacks and chaining

Is there a difference between promise.then.then vs promise.then; promise.then


仅供引用,您可以重新组织上面的代码,使其更加简洁,如下所示:

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

关于javascript - 使用 Promises 的多路流的正确模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40412087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com