Skip to main content

Use the button in the demo to display the content.

Notice the resource that I’m loading in the CodePen demo:

fetch('https://codepen.io/impressivewebs/pen/KKVopdL.html')

That’s a separate CodePen file that I created. CodePen allows you to append .html, .css, or .js to any CodePen URL to request that pen’s HTML, CSS, or JavaScript content, which is useful when using Ajax or Fetch API requests so you’re not hampered by cross-origin limitations. So that’s pretty useful! Try changing the URL to request the CSS or JavaScript (i.e. using KKVopdL.css or KKVopdL.js at the end of the URL) to see the results.

Now that you’ve seen a basic Fetch API example, I’ll introduce you to the different parts of that request.

The resource location parameter

As already discussed, the only argument that’s required when using the fetch() method is the resource. This will usually be a direct URL to the resource being requested, but it can also be a Request object. All the examples I’m going to use in this tutorial will incorporate a direct URL reference, which is the most common way you’ll see fetch() used.

Let’s look at some examples using a direct URL to various free APIs as the requested resources (i.e. the resources I want to ‘fetch’).

Here’s a request for some basketball data:

fetch('https://www.balldontlie.io/api/v1/teams/28')

Here’s a request for JavaScript jobs in the New York area:

fetch('https://jobs.github.com/positions.json?description=javascript&location=new+york')

And here’s a request for a random beer:

fetch('https://api.punkapi.com/v2/beers/random')

Any of those URLs can be viewed directly in your browser and they all involve resources from various free APIs. You can try out other free APIs by visiting this GitHub repo. Just make sure you choose one that doesn’t require authentication (i.e. it has “No” under the “Auth” column).

The returned Promises in a Fetch API request

Every fetch() method begins the process of requesting a resource and returns a Promise. A detailed discussion of JavaScript Promises is out of the scope of this tutorial, but I’ll cover enough for you to be able to work with fetch().

According to MDN, a Promise is an object that:

[…] represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

If I were to convert a Promise into a couple of English sentences, it might look like this:

Do something. When that “something” is finished, do something else.

Of course, that’s an oversimplification, but the concept is more or less there. You’re basically ‘promising’ something then you’re responding when that ‘something’ is completed. And because this is done asynchronously, you can run other lines of JavaScript while the Promise is in the process of being fulfilled.

In the code I used earlier, there are two Promises being returned, one for each .then() method call:

.then((response) => { return response.text(); }) .then((data) => { });

These .then() methods are doing what’s referred to as chaining, which is possible and quite common with Promises. As MDN explains:

If the function passed as handler to then returns a Promise, an equivalent Promise will be exposed to the subsequent then in the method chain.

So to summarize that example code: I’m ‘fetching’ a resource; ‘then’ I’m returning a response; ‘then’ I’m returning the data after reading the response.

The Promise response in a Fetch API

Notice again in the example code the following syntax:

.then((response) => { }

Passed inside the .then() method is an arrow function. The .then() method, which is a feature of JavaScript Promises, takes an argument that’s called an onFullfilled function. This is the arrow function that’s passed as the argument. This arrow function, in turn, is passing in what’s referred to as the Response object.

When the Promise is fulfilled, the Response object is what’s returned, and this is passed into the function from where it can be handled in a number of ways, which I’ll discuss next.

Useful properties & methods of the response object

There are a number of different properties and methods available on the response object once it’s received from the fetch() request. Here are a few useful ones:

  • Response.ok – This property returns a Boolean indicating whether the request was successful.
  • Response.status – This property returns the status code of the response (e.g. 200 for a successful request).
  • Response.url – This property returns the URL of the request. Normally you’d have this when initially sending the request, but if you’re creating the request dynamically, this might be useful.

View a full list of properties in this MDN’s article.

There are also some useful methods you’ll want to be familiar with:

  • Response.clone() – Creates a clone of the Response object
  • Response.text() – Returns the data in the response as text, which is useful when retrieving HTML
  • Response.json() – Returns the data in the response as a valid JSON object, which is useful when retrieving a JSON string.
  • Response.blob() – Returns the data as a blob, which is useful for data that’s in the form of a file reference (like an image URL).

Again, you can view a full list of valid methods in this MDN’s article.

Reading the response

You’ll notice in my example that I’m including two chained .then() methods when dealing with the content being requested. The first .then() is where I’m dealing with the response object and the second .then() is where I’m dealing with the data after it’s been read (usually via one of the methods mentioned in the previous section).

Once the response is received and I’ve chosen what to do with it (e.g. read it as text or as a JSON object), then I can pass it to the next function in the next .then() call. When that subsequent Promise is fulfilled, I’m able to manipulate the data however I want.

This is similar to how Ajax calls work. Whether I’m working with Ajax’s XMLHttpRequest or the Fetch API, once I’ve received the data in a usable format on the current page, I can do with it what I like.

When is a Fetch API request considered rejected?

An important distinction to make when looking at successful and unsuccessful Fetch API requests is when considering network errors vs. HTTP errors.

When making a fetch() request, if permission is not granted to the document that initiated the fetch, then this is considered a rejected request. This occurs at the network level. However, if a fetch request is asking for content that doesn’t exist on the server, this is still considered a successful request, so the Promise is viewed as successfully fulfilled.

To illustrate, take a look at the following CodePen:

Wp-dd.com

WordPress Design, WordPress Development, cPanel Hosting, Web Design, Web Development, Graphic Design, Mobile Development, Search Engine Optimization (SEO) and more.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.