Working with promises inside an if/else

后端 未结 10 1067
北恋
北恋 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:40

    Similar to other answers here, but you can self execute the async and clean up the condition a bit.

    (async () => {
      const should_do_thing_a = true
    
      const do_thing_a = function() {
        return new Promise(function(resolve, reject) {
          resolve('a')
        })
      }
    
      const do_thing_b = function() {
        return new Promise(function(resolve, reject) {
          resolve('b')
        })
      }
    
      const result = (should_do_thing_a) ? await do_thing_a() : await do_thing_b()
    
      console.log(result)
    
    })()

提交回复
热议问题