5 Examples of Javascript Asynchronous Requests
**** Peaceful Mind Break from Coding ****
**** Peaceful Mind Break from Coding ****
XMLHttpRequest Requests
1. Example: GET
var xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘/server’, true);xhr.onload = function () {
// Request finished. Do processing here.
};xhr.send(null);
// xhr.send(‘string’);
// xhr.send(new Blob());
// xhr.send(new Int8Array());
// xhr.send(document);
2. Example: POST
var xhr = new XMLHttpRequest();
xhr.open(“POST”, ‘/server’, true);//Send the proper header information along with the request
xhr.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
}
}
xhr.send(“foo=bar&lorem=ipsum”);
// xhr.send(new Blob());
// xhr.send(new Int8Array());
// xhr.send(document);
Fetch Requests
Fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.
1. Example: GET
fetch(‘examples/example.json’)
.then(function(response) {
if (!response.ok) {
throw Error(response.statusText);
}
// Read the response as json.
return response.json();
})
.then(function(responseAsJson) {
// Do stuff with the JSON
console.log(responseAsJson);
})
.catch(function(error) {
console.log(‘Looks like there was a problem: \n’, error);
});
2. Example: POST
fetch(‘someurl/comment’, {
method: ‘POST’,
body: ‘title=hello&message=world’
})
Async/Await – Try/Catch Requests
Rewrite the Promises chaining using async/await instead of .then/catch:
async function loadJson(url) { // (1)
let response = await fetch(url); // (2)if (response.status == 200) {
let json = await response.json(); // (3)
return json;
}throw new Error(response.status);
}loadJson(‘no-such-user.json’)
.catch(alert); // Error: 404 (4)