Blog

Learn ES6 Today with Vaadin Elements - Part 2: The Fetch API

By  
Juniper Belmont
·
On Feb 14, 2017 3:00:00 PM
·

In this segment of our guide to ES6, you’ll learn how to use the Fetch API to simplify your HTTP requests.

We will be referencing the example we wrote in the previous guide. You can read the first part of this blog series here: https://vaadin.com/blog/-/blogs/learn-es6-today-with-vaadin-elements-part-1-promises

The Fetch API

The Fetch API is not specifically an ES6 update, but rather a new API added to the browser. This API streamlines sending HTTP requests and processing the results. The API is extremely simple, and works entirely with Promises, so it matches up well with our existing code.

Using Fetch is as simple as calling fetch(url). This will run an HTTP GET request against that URL and return a Promise that will resolve to a Response object. From that Response object, you can just call response.json(), which itself returns a Promise will resolve to the results JSON.

Here’s a quick example of fetch:

// send request to url, get a Promise that resolves to the response
fetch(url).then(function(response) {
  // return a Promise that resolves to the response text as JSON
  return response.json();
}).then(function(json) {
  // use the JSON response
  console.log(json);
}

Learn about the Fetch API at MDN

Fetch in action

Let’s take a look at our example again. Follow along on jsbin to try the code yourself.

Since we're only changing the HTTP request code, we do all of our work getJSONPromise. The existing method returns a Promise that resolves to the JSON results, so we'll model our new method to return the same thing.

Our existing code looks like:

function getJSONPromise(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        resolve(JSON.parse(xhr.responseText));
      }
    };
    xhr.open('GET', url, true);
    xhr.send();
  });
}

Following the example above, we can rewrite all of that code to:

function getJSONPromise(url) {
  x = fetch(url).then(function(response) {
    return response.json();
  });
  return x;
}

That’s it!

Browser support

Fetch is currently supported by Edge, Chrome, Opera, and Firefox. Fetch is supported in the next release of Safari (10.1), but not in iOS Safari or IE 11. There is, however a polyfill available here. I have included this polyfill in the example in order to give support for all browsers.

Conclusion

The Fetch API is one more way the web platform is evolving to making coding simpler. Being able to run HTTP requests with one command means you can write the code you want without thinking about the details. When the constructs you use are streamlined, then your code itself will be clearer and more understandable.

In the next episode of our series on ES6 we’ll cover Arrow functions, a quick way to write more readable functions.

Learn more about <vaadin-grid> and Vaadin Elements

Juniper Belmont
Juniper Belmont is a genderqueer developer advocate passionate about the open web platform. They love meeting people, talking about their passions, and giving presentations interspersed with bawdy jokes and lavish, mostly true stories.
They use they/them pronouns and they can be found @juniperbelmont
Other posts by Juniper Belmont