1

Is this valid async/await logic: calling try/catch from within another try/catch?

//within async function...

try { 
    await asyncFunctionFirst();
    } catch (errFirst) {
          try {
              await asyncFunctionSecond();              
          } catch (errSecond) {
              // return errSecond response
          }
      //return errFirst response          
    } 
//return response ok 
t-str-os
  • 57
  • 6
  • 2
    Why wouldn't it be valid? – Aluan Haddad Dec 01 '17 at 12:41
  • Wasn't sure if the approach is ok or there is more elegant solution that I'm missing. – t-str-os Dec 01 '17 at 12:43
  • No that is the most elegant approach possible (assuming you need to call those methods/perform that logic). The purpose of `async`/`await` is precisely to enable asynchronously logic to be expressed in this fashion. – Aluan Haddad Dec 01 '17 at 12:43
  • According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await 'The await operator is used to wait for a Promise. It can only be used inside an async function.' so, I guess it is valid. Have you tested if it runs? – assembler Dec 01 '17 at 12:44
  • Ok, thank you very much – t-str-os Dec 01 '17 at 12:44

1 Answers1

2

Yes, it's valid syntax. However I would not write it like this. Rather use

try { 
    await asyncFunctionFirst();
    return …; // response ok 
} catch (errFirst) {
    try {
        await asyncFunctionSecond();
        return …; // errFirst response
    } catch (errSecond) {
        return …; // errSecond response
    }
}

(if you would also want to catch exceptions from the parts - if not, your version is fine, for alternatives see here)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375