From XHR to Fetch With Async/Await on the Finish Line

From XHR to Fetch With Async/Await on the Finish Line

XMLHttpRequest Synchronous

Long before async JavaScript was a thing, we used the XMLHttpRequest (XHR) to call an API to get data without refreshing our page.

The XHR is event-based. So when we used to make an AJAX call, all the code below the call had to wait until we got our response back from the server (aka synchronous). Our JavaScript was blocking all the other code.

If we got back an error, instead of the response we expected, then the errors in our JavaScript became huge:

In the example below, you can see that this XMLHttpRequest is blocking everything below it, until there is a successful message back from the API.

XMLHttpRequest Asynchronous

We don’t want our code to pause until our response is back from the server.— we want to get back when we’ve received the result from the server.

Luckily, there is a way to make the XMLHttpRequest asynchronous, with the async parameter.

We do this by changing the xhr.open(“GET”, url, false); to xhr.open(“GET”, url); because if we skip the latest parameter in the open method, the value will be true for the async parameter.

In the console of the example next, you can see that the console logs for the DOM manipulation come first because the XHR is async now.

Fetch: Making Promises-Based Asynchronous AJAX Requests

The Fetch API is a new, more powerful replacement of the XHR — fully async and Promise-based.

fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});

If you ask me, you can read the fetch makes more sense, since you can read in order which steps it takes. If you want to read in more detail how to use the Fetch API, Mozilla has a great resource on that.

In the example below, you can see that the Fetch API works in an async way. First, the console.logs from the DOM changes are visible in the console.

Async/Await: Async AJAX Calls In a Synchronous Readable Way

(async () => {
const resp = await fetch("https://api.github.com/users/github");
const jsonData = await resp.json();
console.log("jsonData: ", jsonData);
})();

To use await with the Fetch, we have to wrap it in a async function. In this case, we wrapped it in an IIFE (Immediately Invoking Function Expression).

When the fetch has returned a Promise the first time, the result is put in the const resp, so the next variable waits until the fetch gets a response. The console is only outputting data when the jsonData variable has got the data.

You can see how it works in this example:

The great thing about all of this is it’s not that hard anymore to do async AJAX requests with JavaScript. But it does matter for you and your team which method you use.

XMLHttpRequest has been widely used and supported for years. The [Fetch](https://caniuse.com/#feat=fetch) API is also widely supported, but if you want to support IE11 you need to consider using Babel.

The support of Async/Await is great in all modern browsers, but for IE11 you still need to use Babel in order to use it for development.

Enjoy experimenting with Async JavaScript! And as always, if you have questions or need help— let me know!

divider-byrayray.png

Thanks!

hashnode-footer.png

After reading this story, I hope you learned something new or are inspired to create something new! 🤗 If so, consider subscribing via email (scroll to the top of this page) or follow me here on Hashnode.

Did you know that you can create a Developer blog like this one, yourself? It's entirely for free. 👍💰🎉🥳🔥

If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DM's are always open 😁

Did you find this article valuable?

Support Dev By RayRay by becoming a sponsor. Any amount is appreciated!