Home > Web Front-end > JS Tutorial > How to Correctly Use Async/Await with Try...Catch in TypeScript?

How to Correctly Use Async/Await with Try...Catch in TypeScript?

Linda Hamilton
Release: 2024-12-11 02:11:10
Original
320 people have browsed it

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
}
Copy after login

Handling Errors from the Promise

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

  1. Declare Variable Outside and Branch:

    • Assign a default value to the variable in the catch block.
    • Return early or re-throw an exception from the catch block.
    • Set a flag to indicate whether the catch block caught an exception.
    • Test the variable's value to determine if it was assigned.
  2. Test Caught Exception Type:

    • Test the caught exception against a specific error type.
  3. Use then with Callbacks:

    • Write two callback functions, one for success and one for error, instead of using try/catch.

Example:

await this.User.create(userInfo).then(createdUser => {
    // Business logic goes here
}, error => {
    console.error(error); // From creation
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template