Here's an example of how to use async/await
with fetch
that also handles errors with catch
:
index.tsx186 chars10 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