DEV Community

Cover image for Start trying to make Fetch happen
Iris Silverman
Iris Silverman

Posted on • Edited on

Start trying to make Fetch happen

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 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

Take a look at this simple example from MDN's AJAX resource guide:

Screenshot of an XMLHttpRequest from MDN

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

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

Fetch made things much simpler.

Still image from the movie

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.

    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!
Enter fullscreen mode Exit fullscreen mode

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

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

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...

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."
Enter fullscreen mode Exit fullscreen mode

Resources used during the making of this post:

Top comments (0)