The Better Version of an XMLHttpRequest
I’ve been working on writing some client-side JavaScript recently, including my recent Password Strength Checker, and in the process of making these programs, I have discovered some new JavaScript functions that makes the development process much easier and simpler.
Asynchronous Functions
Before we jump into the fetch
function, let’s quickly cover how asynchronous functions work. The beauty of asynchronous functions is they can be called using two different methods: using promises, and using the await
keyword.
First, let’s take a look at how an asynchronous function looks:
async function myAsyncFunction(){
...
return something;
}
Unlike normal JavaScript functions, an asynchronous function can wait for other resources (like an ajax request). When calling an asynchronous function, you can wait for the result by treating it like a promise, or, if you’re calling it from another asynchronous function, using the await
keyword. Let’s take a look at how each of these would work:
//treat the function like a promise
myAsyncFunction().then(response=>{
//do something
}).catch(error=>{
//do something else
});
//using the await keyword
let result = await myAsyncFunction();
Personally, whenever possible, I like to use the await method, since the code that uses the result can be in the same block (instead of the .then` function).
Fetch instead of XMLHttpRequest
As someone who avoids libraries at all costs, I used to use XMLHttpRequests for every ajax request I would make. However, those requests can get kind of tedious to write. If you’re making a POST request, make sure you include the multipart/form-data
header, or the data won’t go through. Make sure you’re checking the state of the request in the listener, or you might be trying to handle the data before it’s ready.
Instead of using the XMLHttpRequest object, I started using the fetch
function. the fetch API is an asynchronous function that makes the request and returns the response data. You can also manipulate headers, form data, and anything else you might need to deal with right in the function. Here’s an example of how the fetch
function works:
let requestObject = await fetch('https://example.com');
let jsonData = await request.json();
And just like that, with two simple lines of code, you can get a JSON object from a site. You can also use request.text()
to get the text content.
So there you go, ditch the XMLHttpRequest, and write some vanilla code that can easily get a response from a web page. Happy coding!