Some developers are still new to async/await in Javascript. If you’re used to callbacks or using .then to get the value of a promise, async/await can be a bit of a black box, especially when it comes to errors.
The most straightforward and recommended way to handle errors is using try/catch
. This will allow you to catch errors if your async function rejects or throws an error.
async function getProducts() { try { const response = await fetch('/products'); const products = await response.json(); } catch(err) { console.error(err); } }
If you had a function which handles API requests, you could do something like this:
async function request(endpoint) { const response = await fetch(endpoint); return response.json(); } async function getProducts() { try { const products = await request('/products); } catch (err) { console.error(err); } }
You can even make the request
method shorter by doing this:
async function request(endpoint) { return (await fetch(endpoint)).json(); }
My preference when working with promises is to always use async/await
and break my logic for fetching content into separate functions. I tend to exclusively work with native Fetch these days and find breaking up my code makes it easier to work with.