To use async/await with fetch in JavaScript:
index.tsx286 chars13 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