async await fetch response error in javascript

To use async/await with fetch in JavaScript:

index.tsx
async function fetchData() {
  try {
    const response = await fetch('https://example.com/data');
    if (!response.ok) {
       throw new Error(response.statusText);
    }
    const data = await response.json();
    console.log(data);
  } catch(error) {
    console.log(error);
  }
}
286 chars
13 lines

We define a function fetchData() with the async keyword. We use the await operator to asynchronously get the fetch response. If the response is not okay (such as a 404 or 500 status code), we throw an error with the response status text. If the response is okay, we use the await operator again to extract the JSON data from the response.

If the promise returned by fetch is rejected or there is an exception thrown within the try block, we catch the error with the catch block and log it to the console.

gistlibby LogSnag