From XHR to Fetch with Async/Await on the finish line

JS dev Ray
Mar 3 · 4 min read


XMLHttpRequest Synchronous

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

function AJAX(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.send(null);
if (xhr.status === 200) {
console.log(xhr.responseText);
cb(xhr.responseText)
}
}
AJAX('https://api.github.com/users/github', function(data) {
console.log('AJAX: ', data)
})

XMLHttpRequest Asynchronous

But we don’t want our code to to pause until our response is back from the server. We just want to get back when we have recieved the result from the server.

Posibilities with the XMLHttpRequest open method https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open

Fetch: making Promises based Asynchronous AJAX requests

The Fetch API is a new and 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));
});


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);
})();


Mr Frontend Community

Mr Frontend encourage developers that want to grow their skillset! Want to join a community of developers & nice coaches? Join on slack: https://publicslack.com/slacks/mrfrontend/invites/new

JS dev Ray

Written by

Javascript Developer

Mr Frontend Community

Mr Frontend encourage developers that want to grow their skillset! Want to join a community of developers & nice coaches? Join on slack: https://publicslack.com/slacks/mrfrontend/invites/new