5 Examples of Javascript Asynchronous Requests

One of JavaScript’s greatest assets is its non-blocking properties, or that it is an asynchronous language.Websites, like newspaper websites, take advantage of these non-blocking properties to provide a better user experience. Generally, a site’s code is written so that users don’t have to wait for a giant image to load before being allowed to read the actual article—rather, that text is rendered first and then the image can load in the background.
JavaScript uses an event loop to handle asynchronous function calls. When a program is run, function calls are made and added to a stack. The functions that make requests that need to wait for servers to respond then get sent to a separate queue. Once the stack has cleared, then the functions in the queue are executed.
Web developers use the event loop to create a smoother browsing experience by deciding when to call functions and how to handle asynchronous events which is called Asynchronous JavaScript and XML, or AJAX.

**** 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);

Check resource

 

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’

})

Check resource

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)

Check resource

Share This