Fetch and then, and then

Carissa Sarreal
2 min readJun 19, 2021

An analogous tale of how fetch and .then work in Javascript.

Fetch is a function that interacts with a database by retrieving, uploading, editing, and deleting data. One of the best ways I can understand coding concepts is to translate them into a real life scenario. This is an excerpt from one of our study sessions my classmates and I had to better explain this crucial part of Javascript functions.

Mary and Nellie are opening a grocery store. They’ve signed the lease for the space, they’ve decorated and designed the interior displays, they have all the aesthetic bells and whistles to make it look beautiful for customers to come in and check out the merchandise. Did the store come with the merchandise when the store launched? How will they fill their shelves with products to display? They have to get the products from somewhere. From where? From who? Who is carrying these products? Perhaps a warehouse out back?

Yes! Say there is a stockroom or warehouse of some kind in the back- a space no one is looking at, but it stores all of the goods. The warehouse is the backend database. The grocery store itself is the frontend — the visual appeal to guests/users who visit your site. Guests/users do not see or visit the warehouse / database. But Mary and Nellie know what’s in there to be able to render what the frontend requests.

And then this is house fetch works…

Mary tells Nellie the fruit aisle needs some apples. She tells Nellie, “Go the warehouse, and fetch me 200 apples.” Nellie complies. She goes to the stockroom, she fetches the requested goods, and then she returns to Mary with the apples in arms exactly as she was told to do. If this was a real life scenario, Nellie might instinctively bring the apples to their designated shelf. But for our analogy, Nellie is just the function. Now we have Nellie just standing there in front of Mary, with the objects at hand, awaiting her next command. Mary follows up with, “Thank you for the apples you’ve fetched for me. And then…. I’d like you to take the apples to the produce aisle, and then arrange them on the shelf.”

When we make a fetch request to the backend that holds all of our data, fetch is simply retrieving at this point if that is what you asked fetch to do. The data comes back to you. It is then you have the function manipulate the data how you like. In most cases, we JSON-ify the data. AND THEN (the second .then here) we can take this date and display it to the front how we would like.

Mary can ask Nellie, after fetching the apples, to then make apple pies from them, and then place them on display in the pastry aisle.

This is my rendition of how fetch and then work in Javascript.

--

--