javascript - 使用 js 承诺的复杂决策树
问题描述
我正在尝试考虑在使用javascript承诺时格式化复杂决策树的代码的最佳方法。
我已阅读以下问题,但找不到我要查找的内容:
我的愿望:
- 对于将来进入项目的新开发人员来说,流程必须非常容易理解。
- 每个动作/步骤都将在一个独立的功能/承诺中处理,并且可以轻松替换,而无需再次测试其他步骤。
- 输入应该从每个承诺流向下一个承诺。
我想到了以下方法:
方法一
var path = "";
var input = {hhh:111};
step_1(input)
.then(step_2)
.then(change_path_to_A_or_B_according_to_input)
.then(step_a1)
.then(step_a2)
.then(change_path_to_X_or_Z_according_to_input)
.then(step_x1)
.then(step_x2)
.then(step_z1)
.then(step_b1)
.then(step_b2)
.then(step_b3);
在这种方法中,每个步骤或连接将首先检查路径变量,然后决定它是否应该运行。改变路径比较困难,因为步骤的内容应该根据它们在决策树中的位置而改变(即路径变量的检查应该调整)。但是,通过查看决策树很容易理解它,尽管缩进是手动的并且实际上没有任何效果。
方法二
var input = {hhh:111};
step_1(input)
.then(step_2)
.then((input) => {
if(condition) {
return
step_a1(input)
.then(step_a2)
.then((input) => {
if(condition) {
return
step_x1(input)
.then(step_x2);
} else {
return
step_z1(input);
}
});
} else {
return
step_b1(input)
.then(step_b2)
.then(step_b3);
}
});
在这种方法中,改变路径相对容易,因为只需要调整树本身。但是,它的可读性较差。
有更好的建议吗?
解决方案
方法1是一个线性promise链,它的缩进是任意的,不一定与你的内部控制流有关。
方法 2 是正确的方法 - 这就是您在承诺链中执行条件的方式。为了更好的可读性,请使用不同的缩进样式和三元运算符
step_1({hhh:111})
.then(step_2)
.then(input => condition
? step_a1(input)
.then(step_a2)
.then(input => condition
? step_x1(input)
.then(step_x2)
: step_z1(input)
)
: step_b1(input)
.then(step_b2)
.then(step_b3);
);
或使用async
/await
语法:
var input = {hhh:111};
input = await step_1(input);
input = await step_2(input);
if (condition) {
input = await step_a1(input);
input = await step_a2(input);
if (condition) {
input = await step_x1(input);
input = await step_x2(input);
} else {
input = await step_z1(input);
}
} else {
input = await step_b1(input);
input = await step_b2(input);
input = await step_b3(input);
}
推荐阅读
- java - 将数据发送到 Firebase 实时数据库而不删除现有数据
- javascript - 本地主机上的 Google API 密钥限制
- reactjs - 自定义 React Native Carousel 的解决方案,例如示例图像
- batch-file - 根据部分名称将文件移动到文件夹中,但不先创建文件夹
- android - Glide 无法将图像下载到 ImageView
- go - 将结构字段转换为字符串
- android - CryptographyManager 使用的 secretKeyName 是什么?
- c++ - 我不知道为什么它不打印链接列表
- vue.js - 从 vue.js 中的 slot 访问组件数据(没有在郊区声明模板)
- reactjs - 使用 ThreeJS 和 React 三纤执行 React 应用程序时出现“编译失败”错误