javascriptpromiseasync-awaittry-catchecmascript-2017

Correct Try...Catch Syntax Using Async/Await


I like the flatness of the new Async/Await feature available in Typescript, etc. However, I'm not sure I like the fact that I have to declare the variable I'm awaiting on the outside of a try...catch block in order to use it later. Like so:

let createdUser
try {
    createdUser = await this.User.create(userInfo)
} catch (error) {
    console.error(error)
}

console.log(createdUser)
// business
// logic
// goes
// here

Please correct me if I'm wrong, but it seems to be best practice not to place multiple lines of business logic in the try body, so I'm left only with the alternative of declaring createdUser outside the block, assigning it in the block, and then using it after.

What is best practice in this instance?


Solution

  • It seems to be best practice not to place multiple lines of business logic in the try body

    Actually I'd say it is. You usually want to catch all exceptions from working with the value:

    try {
        const createdUser = await this.User.create(userInfo);
    
        console.log(createdUser)
        // business logic goes here
    } catch (error) {
        console.error(error) // from creation or business logic
    }
    

    If you want to catch and handle errors only from the promise, you have three choices: