Better Programming

Advice for programmers.

Follow publication

Member-only story

Be the Master of the Event Loop in JavaScript (Part 3)

Moon
Better Programming
Published in
4 min readDec 26, 2019

Photo by Aaron Andrew Ang on Unsplash

This is the last series of the JavaScript event loop. If you haven’t read my previous post, I recommend you read those first.

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:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Moon
Moon

Written by Moon

Frontend React w/ Typescript developer based in S.Korea. Interested in UX/Testing/FE. mgyang95@gmail.com

Responses (1)

Write a response