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?
