我有一个条件语句,其中我需要执行两个操作之一,然后在任一操作解决后继续。所以我的代码目前如下所示:
if (shoud_do_thing_a) { //should_do_thing_a is just a variable that determines which function to call. it is not a promise
do_thing_a()
} else {
do_thing_b()
}
// more code
问题是两者do_thing_a
and do_thing_b
返回承诺,并且在执行的任何一个解决之前我无法继续。我想出的解决这个问题的最好方法是这样的:
var more_code = function () {
// more code
}
if (shoud_do_thing_a) {
do_thing_a().then(more_code)
} else {
do_thing_b().then(more_code)
}
我不喜欢这个结构。很难跟上,因为你需要跳来跳去才能找到位置more_code
被定义(想象我在几个位置都有这种类型的控制流),而不是简单地能够继续阅读。
javascript中有没有更好的方法来处理这种类型的事情?
如果你可以使用 async/await
async function someFunc() {
var more_code = function () {
// more code
}
if (shoud_do_thing_a) {
await do_thing_a()
} else {
await do_thing_b()
}
more_code()
}
或者如果你不能,使用then()
:
var more_code = function () {
// more code
}
var do_thing;
if (shoud_do_thing_a) {
do_thing = do_thing_a()
} else {
do_thing = do_thing_b()
}
do_thing.then(more_code)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)