Asynchronous JavaScript

When I first started with JavaScript I had a difficult time understanding what asynchronous meant and how to use it to my advantage.

Lets say I wanted to make a GET request to retrieve some date from my database. That request would not happen instantaneously, I couldn’t instantly save the result to a variable name. There are two ways of dealing with this, non-blocking and blocking. In some languages such a Ruby when the GET request is executed the interpreter will pause and allow the request to be completed and then save the result somehow, that’s known as blocking. In JavaScript, the interpreter will continue running the next line of code. This can be accomplished by using promises. What promises do is they can take an HTTP request in addition to a callback function. This allows the request to be made and run some additional code on the data that has come from a request.

This process is known as AJAX, Asynchronous JavaScript and XML. It is the use of the XML HTTP Request objects to communicate with server-side scripts.

The advantage to using AJAX as apposed to blocking methods is performance. Imagine if every time the server need to make a GET request the webpage would hang waiting for the result to come back. This would result in a negative user experiencer. With AJAX multiple request can be made asynchronously, making for a smoother user experience.

The following is an example of how a promise can be used. The promise takes a callback function.

var p = new Promise(function(resolve, reject) {

if(condition) {
resolve('Completed');
}
else {
reject('Failed');
}
});

p.then(function() {
  // The actions you want performed with the data go here. 
}).catch(function() {
  // Return an error.
})