I'm trying to think of the best way to format the code of a complicated decision tree while using javascript promises.
I've read the following questions but couldn't find what I'm looking for:
- How to create a tree of promises?
- How do I catch ES6 promise rejections and completely stop flow?
- Recursive promises to create tree
- 2ality : -Promise trees
My desires:
- The flow must be very easy to understand to new developers who'll enter the project in the future.
- Every action/step will be handled in an isolated function/promise, and could be replaced easily, and without having to test other steps again.
- The input should flow from each promise to the next.
A simple decision tree for example:
I thought about the following methods:
Method 1
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);
In this method, each step or junction will first check the path variable and then decide if it should run or not. Changing the path is relatively hard, because the content of the steps should change according to their location in the decision tree (i.e. the path variable's examination should be adjusted). However, it quite easy to understand the decision tree by looking at it, although the indentation is manual and doesn't really have any effect.
Method 2
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);
}
});
In this method, changing the path is relatively easy, because only the tree itself should be adjusted. However, it's less readable.
Any better suggestions?