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 
5
  • 2
    Why wouldn't it be valid? Commented Dec 1, 2017 at 12:41
  • Wasn't sure if the approach is ok or there is more elegant solution that I'm missing. Commented Dec 1, 2017 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. Commented Dec 1, 2017 at 12:43
  • According to developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… '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? Commented Dec 1, 2017 at 12:44
  • Ok, thank you very much Commented Dec 1, 2017 at 12:44

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.