Home >Web Front-end >JS Tutorial >How to Correctly Use Async/Await with Try...Catch in TypeScript?
Correct Async/Await Syntax for Try...Catch with Variable Declaration
The new Async/Await feature in TypeScript allows for flatter code, but the placement of variables within try...catch blocks when using await can be confusing.
Best Practice
It is considered best practice to include multiple lines of business logic within the try body, ensuring that exceptions are properly caught.
try { const createdUser = await this.User.create(userInfo); // Business logic goes here } catch (error) { console.error(error); // From creation or business logic }
Handling Errors from the Promise
If you only want to catch and handle errors from the promise itself, you have three options:
Declare Variable Outside and Branch:
Test Caught Exception Type:
Use then with Callbacks:
Example:
await this.User.create(userInfo).then(createdUser => { // Business logic goes here }, error => { console.error(error); // From creation });
The above is the detailed content of How to Correctly Use Async/Await with Try...Catch in TypeScript?. For more information, please follow other related articles on the PHP Chinese website!