JavaScript Data Part 1: Fetch

There are many ways to fetch a resource. The Fetch Standard is an effort to unify the architecture around how JavaScript gets remote data. Fetch had its first GitHub commit May 22nd 2016. So now in May 2017, fetch is still a new, but mostly known, feature of JavaScript widely supported in modern browsers (meaning you can use it, but must polyfill if your targeted browsers are not supported).

Fetch is a method to call a server endpoint. It takes a mandatory argument, the path to the resource being fetched .Fetch gets passed (or creates) a Request object, and it returns Response object. The response is in the form of the well loved promise.

Why Fetch? Fetch can be used to fully replace the XMLHttpRequest object. Fetch boasts a cleaner request API and more robust response functionality. To be clear here, fetch adds Requests and Response primitives. This is a big win and not supported by XHR. These primitives enable us to leverage Service Works where w could not in XHR. Fetch also giver the option to make CORS calls (something XHR cannot do). Fetch brings in cache control. Fetch is much more readable and concise.

For the request, pass in a URL, a method type (GET, POST, etc.), some headers, maybe some credentials to the Request object. Is it a CORS call or not? Then give it to fetch().

Read the fetch request API if you want to know all the features available.

After fetch gets your data and its promise resolves, then() is called and passed your Request object to be handled (Remember: then() is called when a promise is resolved). The fetch Response object has built in methods to handle how your Response object is going to return data. Most common is the json() method that converts your data to a JSON object.

Response are streams. This opens up the opportunities to read response streams and start rendering views off the uncompleted stream.

Since promises can be chained with .then, you can use this to generalize your code if you are handling many fetch response over and over. You can write functions that return promises that check the status and parse the json, leaving only the data left to be handled. Its nothing too crazy, but it could slim down some code if a lot of fetch calls are going out.

One thing as of May 2017, engineers are still waiting on fetch to be able to cancel requests. It is supposed to be added in the future. We will see… I got word from Reddit that the promise cancellation proposal that would enable fetch to cancel requests was dropped. We may have to wait awhile before we get around to canceling promises.

If you found this helpful at all please hit the button . It helps this post reach more people.

I post on twitter about new article here. I would also really enjoy hearing any response. Just leave them below!

For further reading I would suggest MDN, David Walsh, Jake Archibald, and Matt Gaunt.