linkedin github twitter

Fetch API

What is it?

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set. MDN Web Docs

In short... it's great for working with APIs!

Why not XHR?

Fetch is promised based. Fetch requires less code. You could still access APIs this way...

var xmlhttp = new XMLHttpRequest(); var url = "myTutorials.txt"; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myArr = JSON.parse(this.responseText); myFunction(myArr); } }; xmlhttp.open("GET", url, true); xmlhttp.send(); function myFunction(arr) { var out = ""; var i; for(i = 0; i < arr.length; i++) { out +=`<a href="${arr[i].url}" >${arr[i].display}</a><br>`; } document.getElementById("id01").innerHTML=out; }

Or you could start writing them this way...

fetch(url) .then( response => response.json()) .then(myFunction) .catch( error => requestError(error));

Can I Use It Now?

Can I Use fetch? Data on support for the fetch feature across the major browsers from caniuse.com.

Yes! Well... maybe not with <= IE 11, unless you add a polyfill, or Opera Mini. Or older versions of the Android browser. If any of those are deal breakers, then NO.

Learn In-Depth