英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论