在 if/else 中处理 promise [英] Working with promises inside an if/else

查看:75
本文介绍了在 if/else 中处理 promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a conditional statement in which I need to perform one of two operations, then continue after whichever operation has resolved. So my code currently looks as follows:

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

The issue is that both do_thing_a and do_thing_b return promises, and I can't move on until whichever gets executed has resolved. The best way I've come up with to solve this is like this:

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 的定义位置(假设我在多个位置都有这种类型的控制流),而不是简单地能够继续阅读.

I don't like this structure. It's difficult to follow because you need to jump around to find where more_code is defined (imagine I have this type of control flow in several locations), rather than simply being able to continue reading.

在 javascript 中是否有更好的方法来处理这种类型的事情?

Is there a better way to deal with this type of thing in javascript?

推荐答案

如果可以使用 async/await

If you can use 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():

Or if you can't, use 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)

这篇关于在 if/else 中处理 promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆