Tchiteu Abloh
Tchiteu Abloh

Reputation: 564

When should I use try catch instead of then catch?

The question is simple, but I haven't found the answer anywhere.

When should i use try catch? in the code below I use try catch to handle the return of a request:

async findUsers() {
    this.loading = true;

    try {
        const [users, count] = await this.api.get('/users/list');

        this.users = users;
        this.totalPages = Math.ceil(parseInt(count) / 10);
    }
    catch (error) {
        this.Messages.requestFailed(error);
    }
    finally {
        this.loading = false;
    }
}

Would it be a good practice to use then(...).catch(...)?

Upvotes: 26

Views: 26771

Answers (2)

David
David

Reputation: 218818

The difference is in how you're handing Promises.

If you're using await to handle the Promise then you wrap it in a try/catch. Think of await as a way to make asynchronous operations semantically similar to synchronous operations (at least within the context of the function in which it's being awaited, consuming code notwithstanding).

But if you're not using await and are instead handling the Promise by appending .then() to it then you'd append a .catch() to that chain to catch failures from within the asynchronous operation.

Because a try/catch isn't going to catch an exception that happens from within the asynchronous operation if that operation isn't awaited.

Upvotes: 27

Amaarockz
Amaarockz

Reputation: 4674

When you use promises(asynchronous operations) then you need to handle the exception in case of an error. So In this case you can use .then().catch(err) {}

When you have synchronous code, use try/catch for exception handling.

Upvotes: -1

Related Questions