A simple example of this might look something like the code below.
In the code above, there are two calls to open() and send() as well as two listeners to handle a successful and failure request. The code above isn't that difficult to read, but as you start to add more and more logic and callbacks, it can quickly become messy.
Step forward a few years and we have the fetch API to save the day. Take a look at the code below and compare it to the earlier code example that we looked at.
Woah! Much cleaner and easier to read. You might also notice that there are no callbacks and events, but instead that they have been replaced with the then() method. This method is part of ES6's new Promises functionality and aims to make our code much more readable and easier to understand. If you'd like to learn more about Promises, I recommend checking out this article on HTML5 Rocks for more information.
Okay, so what if I wanted to make a POST request? Well, the code would look a little something like this.
In the example above, you simply change the method to POST and add a body parameter in the fetch options. Not only does using Promises make your code cleaner, but it also allows you to chain code together to share logic across fetch requests. For more information on how to get the most out of Promises, I recommend checking out the promisejs.org website.
At the moment, support for the fetch API is better than you may think! It is supported in the latest versions of Firefox, Chrome, Opera and Chrome for Android.
However, if you would like this functionality to work in older browsers, there is a polyfill available on Github. The polyfill offers browser support for IE9+ and Safari 6.1+.
For further information about the fetch API, I recommend having a look at the following sites: