Now that we have a better understanding of Promise's and how to use async/await, it is finally time to start looking at fetch. the fetch api allows us to fetch data from external sources. Though fetch can handle multiple data types, today we will focus on fetching JSON data, since it is a very easy standard to use as well as being the main data format we use on the web. To test out fetch we are going to use the dog.ceo api, specifically, the random image api. This endpoint will return a json object with a status and an image path
async function fetchDogImage () { const endpoint = 'https://dog.ceo/api/breeds/image/random' const response = await fetch(endpoint) const data = await response.json() console.log(data) // Logs out the data response similar to // { // "message": "https://images.dog.ceo/breeds/bouvier/n02106382_6601.jpg", // "status": "success" // } } fetchDogImage()
Console:
There are many things to go over in this short example. First we create a const to store our url string. Next we call fetch and we pass our endpoint as a param. You probably noticed that we added the keyword await in front of the fetch call. This is because fetch returns a Promise, and if we remember from the last post, we can await a promise. This means that when we call fetch, we stop stop executing the rest of the logic below fetch until the request completes.
Once the fetch is complete, there is on final step we need to take before we can access the response data. The response object that gets returned has many bits of information that we don't need to go over at the moment. The main thing to know is that to get the JSON data that we expect, we need to call .json() on the response object. This will parse the JSON out of the response, we also need to call await on this call, as it takes some time to resolve.
After that we now have a JSON object to work with and can be passed to the rest of your app as any other JSON object.
Now this example is very straightforward but there is one other thing we need to do before we go fetching everything, we need make sure we handle any exceptions that occur during this process. Similar to how we handled errors with async/await, we will wrap everything in a try/catch.
const endpoint = 'https:/badurl' async function expectError() { let data; try { const response = await fetch(endpoint) data = await response.json() } catch (err) { console.log(err) // handle possible error here } console.log(data) } expectError()
Console:
As you can see, this is very similar to what we did early with the standard fetch call, the important thing to note is that we must wrap both the fetch and the .json() calls in the try/catch because either of them can throw errors. Also note that we placed a let data outside of the try/catch, this is so that we have access to the value outside of the scope of the try/catch.
For a more robust understanding of the many options you have with the fetch api, check out the mdn fetch documentation. Now that you know the basics of fetch get out there and start fetching data!!
