0

I want to write a long promise chain in which some items will be skipped based on a condition. Something like this, unfortunately, this is not valid syntax:

function f(condition) {
    A()
    .then (B)
    if (condition) {
        .then(C)
        .then(D)
    }
    .then(E)
}

What is the most graceful way to do what I want? I already have a way to handle data flow, so I'm not worried about the fact that the result of B and the result of D may not look similar. It's just control flow that I'm concerned with.

Joymaker
  • 813
  • 1
  • 9
  • 23

1 Answers1

2

Put the if statement inside the .then() function.

function f(condition) {
  A()
    .then(B)
    .then(arg => {
      if (condition) {
        return C(arg).then(D);
      } else {
        return arg;
      }
    })
    .then(E)
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Barmar, you're close, but actually I wanted to skip both C and D (no else) if the condition is false. – Joymaker Apr 19 '23 at 22:03