Fetch API
References
Introduction
The JavaScript Fetch API allows the web browser to make HTTP requests (which I will explain shortly) to web servers.
("API" means "Application Programming Interface". An API provides code that does specific functions in the browser.)
The Fetch API capability means that there is no longer a need for the XMLHttpRequest object.
As a reminder, the browser's XMLHttpRequest object allows the browser to request data from the Web server. (You can even see "HTTP Request" in the name of this object! Here is where I explain what an HTTP request is.) An HTTP request can do things such as:
- Update a web page without reloading the page
- Request and receive data from a server - after the page has loaded
- Send data to a server - in the background
For those of you who have never used the XMLHttpRequest object, the Fetch API feature of JavaScript probably doesn't sound like a very big deal.
But if you have ever used the XMLHttpRequest object, you will know that the Fetch API is a huge deal.
Arrow Functions
Before we talk about how the Fetch API works, we first need to look at JavaScript Arrow Functions.
Arrow functions were introduced in ES6, which was the second major revision to JavaScript.
JavaScript ES6 is also known as ECMAScript 2015.
All of the major browsers support ES6.
Arrow functions allow a shorter syntax for function expressions.
With arrow functions, you potentially don't need these features of normal functions:
- the function keyword
- the return keyword (sometimes -- see below)
- the curly brackets (sometimes -- see below)
As a reminder, a normal function looks like this:
let myFunction = function (a, b) {
return a * b;
}
The same function, coded as an arrow function, could look like this:
let myFunction = (a, b) => {
return a * b;
}
which doesn't look very much different from a normal function.
But please NOTE that if the function has only one statement that returns a value, you can remove the brackets and the return keyword. So the previous arrow-function example could be greatly simplified to look like this:
let myFunction = (a, b) => a * b;
Here is a sample page which shows all three types of functions:
<html>
<body>
<h1>JavaScript Arrow Functions</h1>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
let normalFunction = function (a, b) {
return a * b;
}
let arrowFunction = (a, b) => {
return a * b;
}
let shortFunction = (a, b) => a * b;
document.getElementById("demo1").innerHTML = normalFunction(3,5);
document.getElementById("demo2").innerHTML = arrowFunction(4,6);
document.getElementById("demo3").innerHTML = shortFunction(7,5);
</script>
</body>
</html>
You can see the above code running here.
Promises
A Promise object contains both the producing code and calls to the consuming code.
The Promise object has a .then method.
Promise.then() takes two arguments:
- a callback function for success
- a callback function for failure
Both callback functions are optional, so you can add a callback for success or failure only.
Here is some sample code of how a Promise works:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Promise Object</h1>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
let myPromise = new Promise(function(myResolve, myReject) {
let x = 0;
// If you want to see an error display, change x to
// something other than 0
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
</script>
</body>
</html>
You can see the above code running here.
Async and Await
Another thing that we need to talk about before we tackle the Fetch API, is the concept of async and await.
The async keyword before a function makes the function return a Promise object.
And the async keyword also makes the function wait for the Promise.
The await keyword can only be used inside an async function.
The await keyword makes the function pause the execution and wait for a resolved promise before it continues.
Here is some sample code that shows how async and await work:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript async / await</h1>
<h2 id="demo"></h2>
<script>
async function myDisplay() {
let myPromise = new Promise(function(resolve, reject) {
resolve("This Promise was fulfilled!!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
</script>
</body>
</html>
You can see the above code running here.
How Fetch Works
Now that we have talked about arrow functions, promises, and async and await, I think we can proceed to talk about the Fetch API.
Following is some sample code that uses the Fetch API. This code will download the contents of file fetch_info.txt from the Web server, and will display it in the paragraph which has an id attribute of "demo":
<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>
<script>
getText("fetch_info.txt");
async function getText(file) {
let myObject = await fetch(file);
let myText = await myObject.text();
document.getElementById("demo").innerHTML = myText;
}
</script>
</body>
</html>
This is the text that is in the file fetch_info.txt:
This is some sample text that we will read from the Web server with the JavaScript fetch API.
You can see the above code running here.