Start trying to make Fetch happen
Tags: javascript, beginners
Published: 2019-09-06 16:50:10

Once upon a time (1998) in the land of JavaScript, clever coders created XMLHttpRequest objects to exchange information between a website and a server. These special objects allow for asynchronous requests, meaning the browser can continue to run and interact with the server while the request is being made. No page reloads necessary!

Check out the [great docs at MDN](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX) to learn more about Asynchronous JavaScript and XML aka AJAX.

But there was a cost…

The code to construct XMLHttpRequest objects and handle the server requests and responses was…not simple. 

That’s right, it was complicated.

![Movie poster for the film "It's Complicated"](https://thepracticaldev.s3.amazonaws.com/i/89n0cr0yzwjratwm3s38.jpg)

Take a look at this [simple example](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started#Step_3_%E2%80%93_A_Simple_Example) from MDN's AJAX resource guide:

![Screenshot of an XMLHttpRequest from MDN](https://thepracticaldev.s3.amazonaws.com/i/zx8qogs91i5mkag9ozz7.png)

##Fetch (and other things) to the Rescue!##

Queue some trumpets and music swells because valiant libraries from across the world swept in to save the day. Libraries like jQuery used helper functions to make AJAX a little less complicated.

![A still image of two couples laughing awkwardly from the movie "It's Complicated" edited to read "It's slightly less complicated"](https://thepracticaldev.s3.amazonaws.com/i/q06vj4mtummackbkgd5e.jpg)

Then Gretchen got her wish and Fetch happened. The Fetch API burst onto the scene (around the time of Chrome 40 ~ 2015).

*Fetch is supported across most major browsers, except IE.*

 The noble quest of Fetch:
> To unify fetching across the web platform — [Fetch Living Standard](https://fetch.spec.whatwg.org/#goals)

Fetch made things much simpler.

![Still image from the movie "It’s Complicated" edited to read "It's even less complicated"](https://thepracticaldev.s3.amazonaws.com/i/bt7nl6yoxlc8bzewogf0.jpg)

##Promises##

Promises are the result of calling an asynchronous function.

>Promise objects represent the eventual completion (or failure) of an asynchronous operation, and its resulting value. - MDN

Because the program can’t say for sure if your asynchronous function will work out, it returns a promise that you can then interact with. 

>A promise is like a box of chocolates, you never know what you are going to get. -FGM

##Then and Catch##

If you've seen Fetch in the wild, chances are you've seen two methods chained with it - .then() and .catch()
The then() method is typically where you handle a successfully resolved promise. Catch() is where you handle failures.

```javascript
	fetch(URL)
	.then(response => response.json())  // parse response with json
	.then(jsonStuff => doStuff(jsonStuff)) 
//calling another function to do stuff with our json parsed response!
	.catch(errors => console.log(errors)) //handle your errors!
```

Fetch uses the GET method by default (see above), to POST, PATCH, DELETE add an object to your Fetch request like so:

```javascript
  fetch(URL, { 
    method: 'POST', 
    headers: {  "Content-Type": "application/json" }, 
    body: JSON.stringify({
      stuff: "hi",
      number: 0 
    })
   })
```

*DELETE only requires the "method" in the request object.*

##Async, await, and the end…##
Wait there’s more! In 2017 Async and Await were introduced with ES2017. They simplify and interact with promises. But that’s a story for another day...

```javascript
const theEnd = () => {
return Promise.resolve("And they lived") } 
const theEnd2 = async () => { const phrase = await theEnd() 
	return phrase + " happily ever"  }
theEnd2().then(response => console.log(response + " after."))
// "And they lived happily ever after."
```

Resources used during the making of this post:
- [MDN: Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)
- [Fetch Tutorial by Sara Vieira](https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data)
- [Flaviocopes.com Fetch Article](https://flaviocopes.com/fetch-api/)
- [Google Developers Article by  Matt Gaunt](https://developers.google.com/web/updates/2015/03/introduction-to-fetch)