Asynchronous Programming & Javascript

Asynchronous Programming & Javascript

Before getting started with asynchronous programming, let first understand why do we need asynchronous programming? Software these days contain huge amounts of code, which execute sequentially. The problem arises when a piece of code takes longer to complete its execution (like fetching huge datasets from an API), which in turn halts the execution of the code below it. These usually lead to frozen interface incase of an UI and long response time for an API.

Here comes asynchronous programming to the rescue. I will say "asynchronous programming" as "async programming" for sake of simplicity sake here onward. Although async programming has been around for quite some time, but in the recent years with the increase in the usage of mobile and web applications; trying to serve great UX and beautiful eye catching UI's to their customers; the usage of async programming has become more important than ever before , especially as all interactive websites served on the web is powered by Javascript, async programming has become a must.

How does async programming work?

Taking the example javascript here, being a single threaded language at a time only a set of instruction has the access to the execution thread, and incase of a GET request to a server and then awaiting for the result is taxing as rest of the logic is kept unattended. Here comes async programming to the rescue. Generally a callback is assigned to an asynchronous code, callback is function which notifies the calling instance the result of the asynchronous code. The simple example of the async programming and callbacks would be setTimeout function available in Javascript.


const run = () => {
   setTimeout(() => {
         console.log("Example of callback");
   }, 2000);
}

run();

In the above piece of code, setTimeout in defined inside the function definition of run, with an arrow function and 2000 ms as arguments. So when run() is called setTimeout is initiated with 2000 ms timeout (becomes an async operation) and after 2000 ms the arrow function is executed as a callback and "Example of callback" get printed on the console.

With the introduction of promises , async-await and try-catch; be it calling an API using fetch(), or using setTimeout() or setTimeInterval() to delay code execution async programming has become easier with modern Javascript applications responsive UI's and automatic data injection into UI without degrading the UX, the due credit goes to async programming.

  • Dipsankar Maity