gpt4 book ai didi

javascript - 在 if/else 中使用 Promise

转载 作者:行者123 更新时间:2023-12-03 12:38:41 25 4
gpt4 key购买 nike

我有一个条件语句,我需要在其中执行两个操作之一,然后在解决任何一个操作后继续。所以我的代码目前如下所示:

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_ado_thing_b返回 promise ,在执行的任何一个解决之前,我都无法继续前进。我想出的解决这个问题的最好方法是这样的:
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)

关于javascript - 在 if/else 中使用 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47083855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com