Sunday, May 19, 2024
14
rated 0 times [  20] [ 6]  / answers: 1 / hits: 7923  / 3 Years ago, tue, september 28, 2021, 12:00:00

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(...)?


More From » asynchronous

 Answers
4

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.


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.


[#818] Wednesday, September 22, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leighrheac

Total Points: 313
Total Questions: 92
Total Answers: 94

Location: Papua New Guinea
Member since Thu, May 7, 2020
4 Years ago
;