#3 Asynchronous Javascript, AJAX and APIs in Node.js
Here is the link to 2nd article of this series: Running Javascript Outside the Browser.
JavaScript is asynchronous in nature and so is Node.
Let’s start by understanding what asynchronous javascript actually is, and also learn about the most popular use cases of asynchronous javascript, which is basically to make so-called AJAX calls to APIs.
Now, to understand what asynchronous javascript code actually is, we first need to understand what synchronous code is, which is basically the opposite of asynchronous.
Most of the codes that we write as a beginner in javascript are synchronous code, and synchronous simply means that the code is executed line by line, in the exact order of execution that we defined in our code, just like in this small example.
So as the first line of code is reached in the execution, it is simply executed in the execution of thread. (Now don’t worry about this execution of thread. It’s not important here, it’s just to make a point of synchronous versus asynchronous code, as you will see next).
All you need to know is that the execution of thread is part of the execution context, which does actually execute the code in the computer’s processor.
But anyway, back to our example code….. the next line (i.e. 2nd line) of code is executed and then the next one, all in sequence.
Each line of code always waits for the previous line to finish execution. Now this can create problems when one line of code takes a long time to run.
For example, in the 3rd line of code, we have an alert statement, which creates an alert window. Now, as we all know, this alert window will block the code execution, right? Nothing will happen on the page until we click that OK button. And only then, the code can continue executing.
And so the alert statement is a perfect example of a long running operation, which blocks execution of the code.
So again, only after we click OK, the window disappears and the next line can run. This is hopefully a nice illustration of the problem with synchronous code.
Now, most of the time synchronous code is fine and makes perfect sense. But imagine that execution would have to wait for example, for a five second timer to finish. That would just be terrible, right?
Because meanwhile, nothing on the page would work during these five seconds.
And so that’s where asynchronous code comes into play.
This example contains the five-second timer that I just mentioned. And if you want, you can pause reading here for a minute and analyze this code before we move on.
Now, the first line of code is still synchronous here, and we also move to the second line in a synchronous way. But here we encountered the setTimeout function, which will basically start a timer in an asynchronous way. So this means that the timer will essentially run in the background without preventing the main code from executing. We also register a callback function, which will not be executed now, but only after the timer has finished running. Now this callback function that I just mentioned is asynchronous javascript. And it is asynchronous because it’s only going to be executed after a task that is running in the background finishes execution. And in this case, that is the timer. So this callback that we just talked about is registered, and then we immediately move on to the next line.
The main code is not being blocked and execution does not wait for the asynchronous timer to finish its work. And that’s the big difference between synchronous and asynchronous code.
Previously we had to wait for the user to click on the alert window to continue execution. And again, that’s because alert is blocking synchronous code, but now with this timer, the callback is actually asynchronous. And so it’s only going to be executed after the timer has finished. And so, therefore, we say that it’s non-blocking because, in the meantime, the rest of the code can keep running normally. Now, when the timer finally finishes after five seconds, the callback function will finally be executed as well. So you’ll see that this callback runs after all the other code, even though in the code, it doesn’t appear at the end. And so basically an action was deferred into the future here in order to make the code non-blocking.
So in summary, asynchronous programming is all about coordinating the behavior of our program over a certain period of time. And this is essential to understand. Asynchronous literally means not occurring at the same time. And so that’s what asynchronous programming is all about. All right.
Now, as we saw in the async example code, we needed a callback function to implement this asynchronous behavior, right? However, that does not mean that callback functions automatically make code asynchronous. That is just not the case.
For example, the Array map method accepts a callback function as well, but that doesn’t make the code asynchronous.
Only certain functions such as setTimeout work in an asynchronous way. We just have to know which ones do and which ones don’t, okay? But please understand this very important fact that callback functions alone do not make code asynchronous, that’s essential to keep in mind.
But anyway, in order to really understand this, let’s see another example. This example is about loading an image.
So the first two lines run in a synchronous way, one after the other. In the second line, we set the source attribute of the image that we selected in the first line. And this operation is actually asynchronous. Setting the source attribute of any image is essentially loading an image in the background while the rest of the code can keep running. And this makes sense, right? Imagine that it’s a huge image, we wouldn’t want our entire code to wait for the image to load. And that’s why setting the source attribute was implemented in javascript in an asynchronous way.
Now once the image has finished loading, a load event will automatically be emitted by javascript. And we can then listen for that event in order to act on it.
Listening for the load event is exactly what we do here in the next line as well. Here we used addEventListener and to register a callback function for the load event.
Just like in the previous example, we provide a callback function that will be executed once the image has been loaded and not right away because again, all this code is non-blocking.
So instead of blocking, execution moves on right to the next line immediately.
Then once the image is completely loaded, it’s displayed on the webpage and the load event is admitted.
And since we’re listening for that event, our callback function is finally executed.
So once more, we deferred an action into the future making the code asynchronous and non-blocking.
And now at this point, I believe that you have a pretty good understanding of asynchronous code.
There’s just one more important thing that I need to mention which is the fact that event listeners alone do not make code asynchronous, just like callback functions alone, do also not make code asynchronous.
For example, an event listener listening for a click on a button is not doing any work in the background. It’s simply waiting for a click to happen, but it’s not doing anything. And so there is no asynchronous behavior involved at all. Now what makes this code example asynchronous is simply the fact that the image is loading asynchronously in the background, but not the fact that we are listening for the load events to happen. So what matters is the asynchronous behavior of a task, like running a timer or loading an image. And there are more examples of asynchronous behavior in javascript like the APIs, or AJAX calls.
And AJAX calls are probably the most important use case of asynchronous javascript. Let’s see what AJAX is all about.
So AJAX stands for Asynchronous Javascript and XML, and basically it allows us to communicate with remote web servers in an asynchronous way. Now in practice, we make AJAX calls in our code in order to request some data from a web server dynamically — without reloading the page so that we can use that data in our application dynamically.
For example, right in the next article, we’re going to make AJAX calls to request data about countries. And we can then use that data about countries to build a small application that shows us information about the country that we’re currently in. And the possibilities and use cases are endless, but more about that in next.
For now, let’s quickly understand how AJAX works.
Let’s say that we have our javascript application running in the browser, which is also called the client. And we want the application to get some data from a web server. And let’s say the data about countries that I was talking about earlier.
So with AJAX, we can do an HTTP request to the server, which has this data. And the server will then send back a response containing that data that we requested. And this back and forth between Client and server all happens asynchronously in the background, just the way we learned before.
And there can even be different types of requests, like GET requests to receive data or POST requests to send data to a server. (But there is a whole lesson about this a bit later to really show you how it all works in detail).
Now, when we’re asking a server to send us some data, this server usually contains a web API. And this API is the one that has the data that we’re asking for. An API is something pretty important, and so let’s now see what an API and web APIs actually are.
First of all, API stands for Application Programming Interface. In general terms, and on the very high level of abstruction, an API is basically a piece of software that can be used by another piece of software in order to basically allow applications to talk to each other and exchange information. And that’s true not only for web development and javascript, but for programming in general.
Now in javascript and web development, there are countless types of APIs, like the DOM API. These are called APIs because they are a self-contained piece of software that allow other pieces of software to interact with them.
Also, we can always implement a small and simple API in a class where we make some methods available as a public interface. So again, objects made from a class can be seen as self-contained encapsulated pieces of software that other pieces of software can interact with. And that fits the definition of API, right?
But now let’s talk about the important type of API that we are actually interested in when we use AJAX. And those are APIs that I like to call Online APIs.
An online API is essentially an application running on a web server, which receives requests for data, then retrieves this data from some database and then sends it back to the client.
When building applications in practice, we simply call these online APIs, and many people will also call these APIs Web APIs, or again, just simply API. The term Online API is actually a term that I came up with myself because the term Web API is actually also used for other things. Now of course we can build our own Online APIs, but that requires back-end development — development with servers and databases and all that. And this is what we’re learning in this course.
We also use 3rd-party APIs — APIs that other developers make available for us most of the time for free. Let’s imagine that you’re building a traveling application, and you have a database with different destinations and tours that you’re offering. So on your own server, you could build your own API that can receive requests from your front end application in javascript and send back the results. That would be your own API hosted on your own server. But that alone would probably not be enough to build a complete application. And so you could also use some 3rd-party APIs. And there are really APIs for everything. In our example, travel application, you could use an API to get weather data in your destinations, data about the destination countries themselves, data about flights, and currency conversion. And you could even use APIs to send emails or text messages or embed Google maps into your applications. As you can see, the possibilities are really endless with APIs, and we can even say that APIs are what made the modern web as you know it possibly in the first place. So using APIs in javascript is super popular and everyone does it all the time, and so that’s why I’m explaining to you all these details.
Now just to finish, let’s quickly talk about API data formats. AJAX stands for Asynchronous Javascript and XML. Remember? So the X there stands for XML and XML is a data format, which used to be widely used to transmit data on the web.
However, these days basically no API uses XML data anymore. The term AJAX is just an old name that got very popular back in the day and is still used today, even though we don’t use XML anymore. So instead, most APIs these days use the JSON data format.
JSON is the most popular data format today because it’s basically just a javascript object, but converted to a string. And so, therefore, it’s very easy to send across the web and also to use in javascript once the data arrives.
All right. Now that we know what asynchronous javascript is, and also what AJAX and APIs are, let’s finally use all this in practice and make our very first AJAX call in the next article.
Follow me & subscribe to my email list on medium: https://medium.com/@ruckaiya.awf5 to be notified of the publication of the next article.