Working with promises inside an if/else

后端 未结 10 884
北恋
北恋 2021-02-02 10:46

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:

10条回答
  •  攒了一身酷
    2021-02-02 11:20

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

    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)
    

提交回复
热议问题