Asynchronous JavaScript Example
In this article, we will see what is asynchronous javascript with example. JavaScript is an asynchronous, blocking, single-threaded language. Let’s learn about what that means in detail.
Asynchronous
If we have two functions that log messages to the console, code executes top down, with only one time executing at any given time. See the example code below:
Ex:
function A(){
console.log('A')
}
function B(){
console.log('B')
}
A()
B()
->Logs A and then
In our above example, we have created two functions A() and B(). See that A is logged before B.
Blocking
Javascript is blocking, which is because of its asynchronous nature. No matter how long a previous process takes, the subsequent processes won’t kick off until the former is completed. So, if function A() has to execute an intensive chunk of code JavaScript has to finish that without moving on to function B(). Even if that code takes 10 seconds or 1 minute. You might have seen this happen in the browser. When a web application runs in a browser and it executes an intensive chunk of code without returning control to the browser, the browser can appear to be frozen, this is called blocking.
The browser is blocked from continuing to handle user input and perform other tasks until the web app returns control to the processor.
Single-threaded language
A thread is simply a process that your javascript program can use to run a task. And each thread can only do one task at a time. Unlike a few other languages which support multi-threading and can thus run multiple tasks in parallel javascript has just one thread called the main thread for executing any code.
This brings us to the point that Javascript is asynchronous, blocking, and single-threaded language in its most form. But as you might have guessed already this model of Javascript creates a huge problem.
For example:
let response = fetchDataFromDB('endpoint')
displayDataFromDB(response)
What if we have a task to retrieve data from the database and then run some code on the data that is retrieved?
We have to wait for the first line for the data to be fetched. When the data finally comes back, we can resume our normal execution. But fetchDataFromDB(‘endpoint’) could take 1 second or even more. During that time, we can’t run any further code.
So, the Javascript simply proceeds to the next line without waiting, we have an error because of data or response. In this case, is not what we expect it to be. So, we need a way to have asynchronous behavior with Javascript. So, the question is how do we cater to asynchronous programming in Javascript?
Asynchronous Javascript Condition
Just Javascript is not enough to achieve that. We need new pieces outside of javascript to help us write asynchronous code. In the front end, this is where web browsers come into play, and in the back end, this is where Node.js comes into play.
Web browsers and Node.js define functions and APIs that allow us to register functions that should not be executed synchronously and should instead be invoked asynchronously when some kind of event occurs. For example, that could be the passage of time (setTimeout or setInterval), the user’s interaction with the mouse (addEvenListever), data is read from the file system, or the arrival of data over the network (callbacks, promises, async-await).
So, this is pretty much what and why of asynchronous javascript.