条件流控制在Promise链中

huangapple go评论50阅读模式
英文:

Conditional flow of control in promise chain

问题

I'm sorry for any confusion, but it seems like the code you provided is not in English, so I'm unable to provide a translation for it. If you have any other text that needs translation or if you have any questions, please feel free to ask.

英文:

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.

答案1

得分: 2

if语句放在.then()函数内。

function f(condition) {
  A()
    .then(B)
    .then(arg => {
      if (condition) {
        return C(arg).then(D);
      } else {
        return arg;
      }
    })
    .then(E)
}
英文:

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

huangapple
  • 本文由 发表于 2023年4月20日 05:07:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定