I like the fetch() function because, for me, it is what crystallized the concepts of data flow, parameters, and the implicit and explicit passing of data into callback functions. Fetch() is also important because it was the first thing that provided me with any context of how modern single page websites work efficiently.
Below is an example of a fetch() function which takes in a data source- here represented here by the variable ‘URL’. In commercial applications the fetch request is made to an API which allows developers to link their applications to other applications.
Once the fetch() request goes out and gets the data it returns a ‘promise’, which contains the response from the data source- here represented by the variable ‘res’.
We then run a .json() function on that response, which returns the data (typically structured in a ‘string-ified’ JSON format) and turns it into a parsable data structure. Only once the promise has delivered the usable data can we then (second .then()) run an operation on that data to manipulate the DOM, which in our example prints the data to the DOM’s console.
JSON is a data structure that is commonly used to send a data across the internet. However, the .json() function is not the only function that can be applied to the data source. We can run .text() which will return the data in text format. Other functions we can run on the data include:
Another interesting aspect of fetch() is how the promises are passed throughout the entire fetch() function implicitly. The example above shows the data being passed explicitly into the second .then function, but we could have just as easily written:
Studying the fetch() function has been an important part of my learning JS.