Member-only story
Be the Master of the Event Loop in JavaScript (Part 3)
XMLHttpRequest, fetch, and Axios
This is the last series of the JavaScript event loop. If you haven’t read my previous post, I recommend you read those first.
- Part 1 — macrotasks, microtasks, execution contexts, event queues and rAF
- Part 2 — Event bubbling, capturing, and delegation
In this post, I will talk about asynchronous functions in JavaScript.
- XMLHttpRequest
- fetch
- Axios
XMLHttpRequest
JavaScript allows you to fetch data in an asynchronous way. The oldest, most classic way is to use XMLHttpRequest
. It’s a constructor function that allows you to send an HTTP request to the server.
const oReq = new XMLHttpReqeust();
Now oReq
has the XMLHttpRequest object. To make an HTTP request, you should open the request first.
oReq.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
The XHR method is not case-sensitive. So, you could even write it like “geT”, since it’ll be uppercased during the process. You can then send the request to the server.
oReq.send();
To receive the response from your request, you should attach a callback function to the XMLHttpRequest object.
oReq.addEventListener('load', function () {
console.log(this.responeText);
});// Result
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Note that you ought to use a normal function rather than an arrow function, since a normal function’s this
is bound to the XMLHttpRequest, while an arrow function is bound to window
. responseText
of XMLHttpRequest doesn’t exist in the prototype chain of e
.
'responseText' in e === false
But, don’t you think it’s strange? I have explained in the previous posts that there are a few types of tasks in JavaScript. But why is it called an asynchronous function?
In WHATWG documentation about XMLHttpRequest sending, it describes it as follows: