The ins and outs of Fetch

Screen Shot 2017-04-28 at 28 Apr 6.18.28 PMAfter cutting my teeth on Ajax by writing code using XMLHttpRequest (XHR), the arrival of Fetch was like a sunny day after a week of rain. Although Fetch uses a now common pattern that has been replicated in a number of popular frameworks, it’s important to understand what Fetch can and can’t do, as well as which browsers support it and which don’t, in order to successfully roll it out in your own code.

Fetch is based on the syntax of Promises, which are ES6 objects that represent values that will eventually be returned by one or more asynchronous operations. Ajax was an obvious application of Promises, and the result was Fetch. The asynchronous nature of Fetch lends itself to a common pattern:

fetch(url).then(function(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return(response.json());
}).then(function(response) {
    updateUISuccess(response);
}).catch(function() {
    updateUIError();
});

The then method enables chaining of functions to a Fetch request, and the results of one function are passed to the next then method as an object. Capping off the statement with the catch method lets you include code to deal with any errors.

Popular frameworks like Angular have also implemented Ajax using the basic syntax of Promises:

$http.get(url)
.success(function(data) {
  vm.events = data.events;
}).error(function() {
  vm.showError = true;
});

Unlike Angular, which builds in robust backward compatibility, using Fetch requires a few extra steps to ensure support in older browsers. GitHub has released a polyfill for Fetch that enables some older browsers to process a Fetch request. Because Fetch is built on Promises, the Fetch polyfill requires use of a polyfill for Promises as well. These polyfills bring support for IE10+ and Microsoft Edge, Safari 6.1+, as well as for very old versions of Chrome and Firefox. So if you need to support very old browsers, and/or more obscure ones, including your own fallback XMLHttpRequest code (and even fallbacks for older Microsoft syntax) will probably be necessary.

For more on working with Ajax in different contexts — including XHR, Fetch, jQuery, Angular, and React — check out my recently released course, Building Web Applications with Ajax, on Lynda.com.

Introduction to Fetch (Google Developers)

Promise (MDN)

Building Web Applications with Ajax (Lynda.com)