Introduction to the Fetch API
In this article, we’ll learn what the new Fetch API looks like, what problems it solves, and the most practical way to retrieve remote data inside your web page using the fetch()
function.
For years, XMLHttpRequest has been web developers’ trusted sidekick. Whether directly or under the hood, XMLHttpRequest
has enabled Ajax and a whole new type of interactive experience, from Gmail to Facebook.
However, XMLHttpRequest
is slowly being superseded by the Fetch API. Both can be used to make network requests, but the Fetch API is Promise-based, which enables a cleaner, more concise syntax and helps keep you out of callback hell.
The Fetch API
The Fetch API provides a fetch()
method defined on the window
object, which you can use to perform requests. This method returns a Promise that you can use to retrieve the response of the request.
The fetch
method only has one mandatory argument, which is the URL of the resource you wish to fetch. A very basic example would look something like the following. This fetches the top five posts from r/javascript on Reddit:
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
.then(res => console.log(res));
If you inspect the response in your browser’s console, you should see a Response
object with several properties:
{
body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://www.reddit.com/top/.json?count=5"
}
It seems that the request was successful, but where are our top five posts? Let’s find out.
Loading JSON
We can’t block the user interface waiting until the request finishes. That’s why fetch()
returns a Promise
, an object which represents a future result. In the above example, we’re using the then
method to wait for the server’s response and log it to the console.
Now let’s see how we can extract the JSON payload from that response once the request completes:
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
.then(res => res.json())
.then(json => console.log(json));
We start the request by calling fetch()
. When the promise is fulfilled, it returns a Response
object, which exposes a json
method. Within the first then()
we can call this json
method to return the response body as JSON.
However, the json
method also returns a promise, which means we need to chain on another then()
, before the JSON response is logged to the console.
And why does json()
return a promise? Because HTTP allows you to stream content to the client chunk by chunk, so even if the browser receives a response from the server, the content body might not all be there yet!
Async … await
The .then()
syntax is nice, but a more concise way to process promises in 2018 is using async … await
— a new syntax introduced by ES2017. Using async Ú await
means that we can mark a function as async
, then wait for the promise to complete with the await
keyword, and access the result as a normal object. Async functions are supported in all modern browsers (not IE or Opera Mini) and Node.js 7.6+.
Here’s what the above example would look like (slightly expanded) using async … await
:
async function fetchTopFive(sub) {
const URL = `https://www.reddit.com/r/${sub}/top/.json?limit=5`;
const fetchResult = fetch(URL)
const response = await fetchResult;
const jsonData = await response.json();
console.log(jsonData);
}
fetchTopFive('javascript');
Not much has changed. Apart from the fact that we’ve created an async
function, to which we’re passing the name of the subreddit, we’re now awaiting the result of calling fetch()
, then using await
again to retrieve the JSON from the response.
That’s the basic workflow, but things involving remote services doesn’t always go smoothly.
Continue reading %Introduction to the Fetch API%
LEAVE A REPLY
You must be logged in to post a comment.