Fetch – Modern Async Server Calls

Being a web developer right now is exciting and confusing. We keep getting new tools, but they all seem to come with more tools of their own.

It's refreshing when we get a near-total replacement for something that is actually simpler. XMLHttpRequest (XHR) is the definition of an old, confusing, complex tool. Fetch API is the simpler replacement.

Fetch vs. XHR?

Fetch is a brand new way of making asynchronous calls to the server. Before we dive into the details, let's look at an example of Fetch versus XHR. To make this simple, we'll just request a file (jQuery in this case) from the Google CDN and just dump it to the console.

Fetch Example

You can run the example code below. You may want to open your F12 network tools to compare it to XHR.

Now, let's take a look at this using XHR.

XHR Example

Again, you can try it below.

This is a pain to write and read. I had to Google what "readyState 4" even meant (request finished and response ready) to write this post. Why do I have to send a null?

XMLHttpRequest is the definition of an old, confusing, complex tool.

In reality, a lot of devs just include jQuery and write this:

$("#basicjQueryButton").on("click", function() {
    // Loading the jQuery code
    $.get("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", function(data) {
        console.log(data);
        alert("Done using jQuery!");
    });
});

We download 34.5KB (as of jQuery 3.1.0), sometimes just for this functionality. You don't need to do this anymore.

Now There Is Fetch

The Fetch API gives us a generic Request and Response that we can use to GET/POST/PUT/DELETE/HEAD data to and from the server. It uses promises which makes it easier to code, as well as much easier to read. Because it is promise-based, it even chains nicely into other methods.

It's useable today in Chrome, Edge and Firefox, and other browsers through a polyfill.

Fetch API Browser Support

Promises?

Before diving into the advanced features of Fetch, let's take a brief look at promises. If you want to learn more, I recommend this really excellent post from Jake Archibald.

Promises are a new way of dealing with asynchronous code in JavaScript that is simpler than chains of callbacks. Promises make it easy to write code that reads like human language. For example, you could write something like this:

LoadMyData()
    .then(ProcessMyData)
    .then(DoSomethingElse)
    .catch(HandleError);

There is a lot more to promises, but for this article you should know the following:
* Promises start off pending
* Promises resolve as either fulfilled or rejected
* Fulfilled promises trigger a .then() call
* Rejected promises trigger a .catch() call
* All of this happens asynchronously, when the previous promise completes

Request & Response Object

The example shown above defaulted to a simple GET and didn't set any advanced headers. However, Fetch allows you advanced control of your Request object before making a request, and lets you query the Response object after.

For example, say your application wants to do the following:

  • Make a CORS request to a remote server.
  • Specify that you're looking for a content type of "application/json"
  • Make sure you don't check cache or store the response in it
  • Verify you got JSON back from the server (or maybe choose how to parse based on the data)

Stream Readers

You may have noticed a call like this above:

response.text().then(function (responseText) {
    console.log(responseText);
    alert("Done using Fetch!");

What I didn't tell you before was that .text() is actually a stream reader. The TL;DR of this is that the response data is a stream of bytes that you can read from. Stream readers pull in the entire stream and parse it for you.

There are a few methods available to you including:

  • .text() – returns the full stream as a string;
  • .json() – returns a JSON object;
  • .formData() – returns a FormData object, which may be useful for posting somewhere;
  • .blob() – returns the stream as a blob, useful if you plan to do non-JS parsing with it;
  • .arrayBuffer() – returns an array buffer, which may be useful for streaming.

If you need to parse the stream twice it's a problem, because once you've read it, it's empty. Fortunately there's one more method:

  • .clone() – creates an identical copy of the response.

Alternatively, you can parse the string manually and do what you want. You can find a good example here (with source), but note that this doesn't work in all browsers yet.

What's the Catch?

Fetch can do nearly everything that XHR can do. The two things that are missing are:

  • Fetch requests can't be canceled. This seems largely due to promises not being cancelable. Luckily, there's a spec in draft for that.
  • Progress is difficult to track. You have to build that yourself. You can see an example of that here from this article by the Edge team.

That's really it. I told you this was a big improvement!

Conclusion

Fetch is a powerful tool you can use today (with or without the polyfill), and it's better than XHR for almost any application. You probably weren't writing XHR yourself, but if you were, life just got better. It's more likely you are using a library like jQuery to simplify your AJAX calls which won't be the case anymore. Fetch really comes into its own when we start looking into Service Workers…but that's a topic for another post.

If you want to take a deeper dive into Fetch, the Mozilla Developer Network is the place to start.

Happy coding!

Comments

  • Eric Lawrence

    It’s not really all that bad.

    XMLHttpRequest.DONE is a constant with value 4, so you needn’t compare to some inscrutable value. You needn’t pass null to send() if you don’t want to.

    • Jared

      Good point about null. I’ve always seen/done it that way I guess. Habit…

      I may have dramatized things a bit, but I do think XHR is confusing, especially if it’s not something you work with every day. I’ve run into a number of cases where that’s the last remaining reason someone includes jQuery as I mentioned in the article. It used to be for compatibility, now more simplicity.

      Thanks for adding to the discussion 🙂

  • ThomasG77

    You may add https://github.com/mdn/fetch-examples to try nearly all fetch examples.
    I would also mention fetch polyfill “as a service” can be done using https://cdn.polyfill.io/v2/polyfill.js?features=fetch

    • Jared

      Good post. Thanks for adding this to the discussion! Polyfill.io looks cool but I haven’t used it on anything yet so I don’t know how it performs vs something you’re serving alongside your app.

  • Just curious, is there any difference of using Fetch over the Async Await. are there any good reasons to use one over another (and vice versa)?

    • Jared

      Good question. They’re different but related things. Fetch is all about getting data back from the server, generally asynchronously (using promises). Async/Await is all about making asynchronous stuff easier. There’s a good example on Jake Archibald’s blog that combines the two: https://jakearchibald.com/2015/thats-so-fetch/

  • Craig Bilner

    Instead of checking that response.status is 200 should it check response.ok?

    https://developer.mozilla.org/en-US/docs/Web/API/Response/ok

  • I’m still not sure why fetch needs to resolve promise twice to get data?

    It looks like it’s still XHR behind the scene – first resolve for DONE and then look for OK.

    • Craig Bilner

      The fetch promise rejects if that actual call fails, rather than it not being an Ok status code. The developer/consumer can then decide how to proceed depending on the status code. As mentioned in the stream reader section, the “second promise” is to provide a nice interface to working with a response that finishes asynchronously such as a stream, which if it was large would just block your thread on receipt while it reads it out.

  • Ян Жабин

    Fetch can’t abort the request and can’t handle a progress (for example uploading/downloading). I you need something like this, please do not use the fetch.

  • I like fetch because it hides lots of complexities of XHR and give us a nice promise based interface. But the name “fetch” is also kind of confusing. In normal English, fetch means getting something. But Fetch in JS can be used to make asynchronous POST call as well which is not what “fetch” means. Does it mean that conceptually XHR,Ajax and Fetch “should be” used for fetching data i.e. making GET request from server and POST call should be synchronous and reloads the complete page?