DEV Community

Cover image for FETCH AND ASYNC JAVASCRIPT
Tate Braeckel
Tate Braeckel

Posted on • Updated on

FETCH AND ASYNC JAVASCRIPT

I have found async and fetch to be particularly frustrating to describe. I understand the process overall, but continue to not find the right words for the process. So here goes a description using my own fetch request in my Phase 1 Final Project. Fetch is an asycnhronous

First I am grabbing my button 'btnGet' with the querySelector, then attaching a 'click' event to that button which executes the 'getMovies' function as a callback. Within the 'getMovies' function the fetch GET request is initiated.

const fetchBtn = document.querySelector('#btnGet');
fetchBtn.addEventListener('click', getMovies);

Enter fullscreen mode Exit fullscreen mode

At that point the code block within the 'getMovies' function fires. First, the fetch method makes an GET http request to the live server/ db.json. A fetch GET request only requires one parameter, the URL of the API or live server you are sending the request to.

That request instantly returns a promise object. The promise object can resolve as 3 types of statuses: pending, resolved, or error. When the promise object returns as resolved it is the entire HTTP response so the readable JSON body needs to be extracted. In the first .then the '(response)' is the value given to the returned/ resolved promise object. The JSON body is extracted from the promise object using the .json()method.

I used an arrow function and the .json as a callback function.

function getMovies() {
    fetch(`http://localhost:3000/movies`)
        .then((response) => response.json())
        .then((data) => {
            movies = data;
Enter fullscreen mode Exit fullscreen mode

A second promise is returned and resolves with the result of the .json() method parsing the body as JSON.

Then, in the second '.then' the new, readable data (parsed json array object) is used in some way through the new arrow function code block. I gave my new data the value of "data" to identify what was returned. I want to take this data, which is movie objects with multiple key/ value pairs, and use that data in some way. Initially I 'console.log(data)' to see what is inside the returned value. What I find is an array of movie objects with different key/ value pairs.

Now that I identified what is usable in the objects I want to use it in some way:
Because the button "fetchBtn" is linked to a click event, I want use this event to print them to the DOM, client side via the "result" <div>that is nested within my API SEARCH BUTTON <div>.

Then I grabbed the 'result' <div>,using a document.getElementById and stored it in a variable named 'result,' so I could use it for my iterator later on. Using dot notation I then assign an empty string to result's textContent. This will allow each new element created by the forEach iteration to replace that empty string content on each pass through.

 let result = document.getElementById('result');

            result.textContent = '';
Enter fullscreen mode Exit fullscreen mode

Now that I have a container to append to, the 'result' div, I want to use a forEach to iterate through the data returned from my GET request. I use the keyword 'data' to call on the data parameter from the fetch request, which will grab all of the array object. Then I use a forEach() method to iterate through all of the objects within the array.

For each object I will append the innerHTML of the 'result' div with a

element and use string interpolation to call on each individual movie's keys of title, genre, and release date.

Within this code block the forEach iterates through each of the objects, inserts the new innerHTML with a <p> tag and prints all of the results to the client side with the <div> id="apisearch".

           data.forEach((movie) => {
                result.innerHTML +=
                    `<p class="movieItem" >${movie.title} is a(n) ${movie.genre} movie that was released in ${movie.release}</p>`
            })
        })
}
Enter fullscreen mode Exit fullscreen mode

I think writing this out helped me feel more comfortable explaining the fetch process. Once it was broken into parts, it made more sense and I could see each action taking place and why.

Top comments (0)