Use the button in the demo to display the content.
Notice the resource that I’m loading in the CodePen demo:
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
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:
And here’s a request for a random beer:
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
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
This article was written by Louis Lazaris and originally published on CodeinWP.