Reputation: 23
This is more of a generic question to do with asynchronous functions rather than a specific issue I am having.
When I create an asynchronous function using 'try' I also use 'catch' to catch any errors. When I then use this function I might want to use '.then'. At this point, I often use '.catch' as well but do I need to? Should I use catch on the function itself as well as when I invoke the function?
For example, consider a simple asynchronous function such as:
async function getData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Something bad happened!');
}
const data = await response.text();
return data;
} catch (error) {
console.warn(error);
}
}
And then you invoke the function and do something with the data:
getData('https://myurl.com')
.then(data => document.querySelector('#app').innerHTML = data)
.catch(error => console.warn(error));
Would the above example be considered 'correct' or should the catch when using the function be removed?
Upvotes: 1
Views: 61
Reputation: 14218
There are some things you should keep in mind:
try{} catch(){}
may be necessary if a function is able to cause an error, do a side effect like logging, or re-throw a more meaningful error.
Say for example, The fetch
url-end point is wrong i-e 404 error
or we have a error right in our JSON. So we much handle such situations. That's where in our async
function try-catch
does come handly.
Using try, catch
at the top level. This will make sure that all our fetch calls within async
function are handled properly.
then. catch
from Promise cannot catch the throw new Error
.
Coming to Part B of your Question. We are using then
block after function because:
Every Async function returns a promise no matter what. Even when nothing is returned from an Async-Function it still returns promise
In your case, throw new Error('Something bad happened!');
is caught in the catch
block below. Let's take a closer look.
async function getData(expectedResult) {
try {
const response = await fakeFetchData(1000, expectedResult);
if (response === 0) {
throw new Error('Something bad happened!');
}
return response;
} catch (error) {
console.log("Oops: " + error);
}
}
function fakeFetchData(ms, expectedResult){
return new Promise(resolve => setTimeout(() => resolve(expectedResult), ms))
}
getData(1).then(d => console.log(d));
getData(0).then(d => console.log(d));
If expectedResult <> 0
, it's fine. Otherwise, It'll log msg like below
Upvotes: 1