Working with promises inside an if/else

后端 未结 10 886
北恋
北恋 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)
    
    0 讨论(0)
  • 2021-02-02 11:26

    Simple working example:

    The scope it's defined in must be async.

    const createUser = async (data) => {
       if (await isUsernameTaken(username)) { return 'username-taken' }
    }
    

    The isUsernameTaken func:

    const isUsernameTaken = async (username) => {
        const request = await API.SomeRequest
        return !request.isEmpty
    }
    
    0 讨论(0)
  • 2021-02-02 11:31
    more_code = miFunc() => return new Promise((resolve, reject) => ... });
    

    Solution 1

    const waitFor = should_do_thing_a ? do_thing_a() : do_thing_b();
    waitFor.then(...).catch(...)
    

    Solution 2

    let waitFor = Promise.resolve();
    
    if (do_thing_a) {
        waitFor = do_thing_a();
    } else {
        waitFor = do_thing_b();
    }
    
    waitFor.then(...).catch(...);
    
    0 讨论(0)
  • 2021-02-02 11:34

    Save the promise and add the then after the if statement:

    var promise;
    
    if (shoud_do_thing_a) {
      promise = do_thing_a();
    } else {
      promise = do_thing_b();
    }
    
    promise.then(more_code);
    
    0 讨论(0)
  • 2021-02-02 11:36

    How I want to improve on other answers:

    • keep it clean and simple
    • no unneeded variables
    • return promise asap
    • in js we use camelCase
    • put it in a function and name that function to keep it readable
    • let then execute moreCode so it's called after the thing is done.

    function doTheThing () {
      if (shouldDoA) return doThingA()
      else return doThingB()
    }
    
    doTheThing().then(moreCode)
    
    0 讨论(0)
  • 2021-02-02 11:36
    var promise = shoud_do_thing_a? do_thing_a: do_thing_b
    
    promise().then(function () {
    // more code    
    })
    
    0 讨论(0)
提交回复
热议问题