首页 > 解决方案 > 使用 js 承诺的复杂决策树

问题描述

我正在尝试考虑在使用javascript承诺时格式化复杂决策树的代码的最佳方法。

我已阅读以下问题,但找不到我要查找的内容:

我的愿望:

  1. 对于将来进入项目的新开发人员来说,流程必须非常容易理解。
  2. 每个动作/步骤都将在一个独立的功能/承诺中处理,并且可以轻松替换,而无需再次测试其他步骤。
  3. 输入应该从每个承诺流向下一个承诺。

例如一个简单的决策树: 示例决策树

我想到了以下方法:

方法一

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

在这种方法中,改变路径相对容易,因为只需要调整树本身。但是,它的可读性较差。

有更好的建议吗?

标签: javascriptpromisedecision-tree

解决方案


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

推荐阅读