The New Fetch Standard

Monday, February 8, 2016

The XMLHttpRequest object has been around, in one form or another, since 1999. XHR has been a key ingredient in most web applications for well over a decade now. During that time various libraries have wrapped the API to make XHR more palatable and easier to use, while vendors have extended the capabilities of XHR to support binary data, cross origin requests, and progress events. It’s been quite the ride, but the future is fetch.

Think of fetch as a modernized XMLHttpRequest. The raw API is easier to use, and all starts with a global fetch method.

var movie = {
    id: 1,
    title: "Star Wars"
};

fetch("/movies", {
    method: "put",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(movie)
}).then(function(response) {
    return response.text()
}).then(function(result) {
     console.log(result);
});
    

With promises now an official part of the JavaScript language, it is nice to see standard APIs using promises instead of callbacks.

Browser support for fetch is coming along (I ran the above sample in Chrome 47), although the API is still a work in progress. The API allows us to influence the caching mode directly ({cache:”reload”}, as one example), which is good, but timeouts and deadlines are still open issues and not yet in the spec.


Comments
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!