async await fetch catch in javascript

Here's an example of how to use async/await with fetch that also handles errors with catch:

index.tsx
async function getData(url) {
  try {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}
186 chars
10 lines

In the example above, getData is an asynchronous function that takes a URL as an argument. Inside the function, we first use the fetch method to send a request to the specified URL. We then use await to wait for the response and convert it to JSON format using the json() method. If everything goes smoothly, we return the data.

However, if an error occurs in any of these steps, the catch block will be executed, and the error will be logged to the console using console.error().

gistlibby LogSnag