As developers, we often need to gather data from external sources for use in our programs. Fortunately, in recent years, the Fetch API has made retrieving, adding, editing, and removing data from external databases more accessible than ever before. This method works by providing and resolving a series of promises. Here are some examples of this process.
What is fetch?
Here we are setting the variable to the image URL and plugging it into the fetch to get images of 4 random dogs. Even though running the code will execute without errors, we won’t be able to do much with it just yet, and by examining the result of this code in the terminal, we’re left with the following:
What is a Promise?
When a Promise is Pending, it means the server hasn’t replied to our request yet. A Pending Promise can be transitioned to either Fulfilled or Rejected. Once a Promise transitions to either Fulfilled or Rejected, it cannot transition to any other state, and its value will not change as well, but until we get a result, the Promise is pending.
When a Promise is Rejected, this means the asynchronous operation has failed, and the Promise will never be fulfilled. Per MDN, the fetch() API only rejects a promise when a “network error is encountered, although this usually means permissions issues or similar.” Basically, fetch() will only reject a promise if the user is offline or some unlikely networking error occurs, such as a DNS lookup failure.
When a Promise is Fulfilled, this means the asynchronous operation has been completed, and the Promise has a value. Back to our dog example, we need to tell our program what to do with the request results, but first, we need to add a Promise.prototype.then method in order to attach a callback once our Promise has been fulfilled. We then want to parse the response as JSON.
Success! We’ve just printed out the JS Object to the console, but now give it instructions to manipulate the DOM with our new JS Object and get four random dog photos to appear in our browser:
Here we have passed our image object to our showImage function. In our showImage function we set the a div variable to grab our dog image container in our index.html page. Then iterate over the images with a forEach method, and create a image element and append the image element to the div variable we set earlier.
There you have it! On each refresh a new set of four random adorable dog photos show up in our browser!