Javascript Asynchronous programming

Madhavi Imashi
5 min readFeb 26, 2022

If you’ve ever been confused about the difference between sync and async calls in JS or if you’re curious to know how to handle async calls in JS, you have found the right blog post. I suggest you read this till the end which would probably take a very few minutes to read completely which I guarantee you won’t regret. Also if you are either someone who doesn’t know what are async functions or you haven’t even heard that before, I suggest you also read this blog till the end so that you might learn something new that you didn’t know before.

Through this blog post, we would mainly understand the real concept behind asynchronous programming, and let’s keep this discussion simple and concise. So spare me a few minutes till you grasp it carefully.

Alright then, let’s get into the topic without further delay.

what is sync and async in javascript?

As I think, the easiest way to understand asynchronous programming is to get a clear idea of what synchronous programming is at first.

normally since JS is a single-threaded language, JS only executes one task at a time without interruption. Therefore, each task will get executed only after the previous task is completed its execution, which we called as synchronous behaviour of JS. if I make it simpler, in the below code snippet, the JS engine creates a blocking state where the 2nd line of the program should wait till the 1st line gets executed. Each execution must happen in order.

console.log(‘this will get executed firstly’)
console.log('this will get executed next')

Okay. now about the Asynchronous part. Suppose you are going to upload a photo to a social media application. Do you need to stay on the same screen that you uploaded the photo waiting for it to complete uploading it? No right? you can either stay or leave or probably go to some other screen while it’s being uploaded. and that is simply what asynchronous programming does. till a particular function gets executed completely, the rest of the program doesn’t need to wait.

so why do we need asynchronous programming?

I hope you now got the point.

Actually, to create a concurrency behaviour within a program written in JS, we need to know about asynchronous programming concepts because normally JS engine only executes one operation at a time, which causes block the rest of the operations from getting executed concurrently.

but still, if you want some task to get executed without waiting for everything previous to get executed, we can do that without any issue and that’s where we get the need for asynchronous programming in JS. simply we can create async calls for such scenarios that could take much time for its execution. then the rest of the code lines will get executed even before the execution of the async call is completed.

Example scenarios when async programming could be useful:

-when fetching data from a DB

-when interacting with an API which possibly can take a few milliseconds more than a normal operation would take.

In Javascript, there are 3 ways to deal with such asynchronous scenarios;

1) callback functions with setTimeout()

2) Promises

3) Async/ Await function

set timeout()

setTimeout() is a method that sets a timer that executes a function or a specified piece of code once the timer expires which is a good way to make async calls.

Example:// 1st task
setTimeout(() => {
console.log("This will be executed after 2 seconds.");
}, 2000);
// 2nd task
setTimeout(() => {
console.log("This will be executed after 5 seconds.");
}, 5000);
// 3rd task
console.log('Hello there:)')
Output:Hello there:)
This will be executed after 2 seconds.
This will be executed after 5 seconds.

In the above example, 1st, 2nd, and 3rd tasks will be called in the correct order but the execution times will differ.

1st task is called firstly and it will wait for 2 seconds to execute. So since setTimeout() is an asynchronous function, while the 1st task is waiting, the 2nd task is called without creating a 2-second pause until the 1st task completes its execution. Similarly, once 2nd task is called, it waits for 5 seconds to execute. meanwhile 3rd task is already executed and 1st task will execute once it finishes waiting for 2 secs from the time it’s been called.

I hope now it’s clear for you how the setTimeout() function works.

But setTimeout() is not always a good approach since there are some issues when using setTimeout for asynchronous codes.

  • Assume you have to write a code to fetch some data from a DB via an API call which normally takes around 3ms to receive the response. So you’re going to use a set timeout function with a time limit of 3ms hoping it would complete the execution of this API call within this time period as usual. What would you think would happen if you get an unexpected network error in the middle and it’s going to take around 6 milliseconds to complete that action. Probably then the API call will not be able to complete within the time limit that you’ve set in the program right? so it will end up failing at run-time which you don’t expect to happen. This is kinda one issue with using setTimeout() to deal with async calls.
  • Another issue is called ‘callback hell’, which can occur due to the redundant creation of callback functions within a program. This reduces the code readability. (if you haven’t heard about callback hell, don’t worry. you are just one google search away if you wanna know it immediately. Also, I will walk you through that from another blog in detail which should be explained separately in a structured way which I didn’t want to do here which could probably make you overwhelmed with everything in one blog.)

Basically, there are a few other ways to address these issues in a set timeout call. That’s obviously by using JS promises or async/await function. They are two alternatives and yet the best options to be used in asynchronous programming.

We will discuss these promises and async/await calls in another blog soon. Until then happy coding!🙌

--

--