Skip to main content

Command Palette

Search for a command to run...

An Intro to Asynchronous JavaScript

Updated
3 min read
An Intro to Asynchronous JavaScript

What is asynchronous javascript?

Javascript has a synchronous nature which means that control passes to the next line only after the line before it has finished execution.

But certain pieces of code do not get executed instantly. Instead, they take some time to process. So, until then where should the control be? Of course in the former line of code, no? But there is a problem with it.

The problem is that the rest of the code will have to wait until the current code is executed. Now, this is not very efficient both from the development perspective as well as the end user's perspective.

To get over this, JavaScript has a concept where it can be made to work asynchronously.

Confused? Well, let me explain.

Whenever JavaScript encounters an asynchronous code, for eg. fetch(), setTimeout() etc, it sends this code to the Web APIs to handle, and the control moves to the next line of code. This means we do not wait for the asynchronous code to finish its execution before moving on to the next line.

But you will ask, "What if we encounter some code later that is dependent on the result of this asynchronous code?"

Well, yes. That is another issue that we got to tackle.

Here we introduce the concept of Callbacks.

Callbacks are functions that are passed as an argument to another function. This callback function can be called anytime inside of the latter function.

Going back to our issue, if any of the latter pieces of code are dependent upon the result of the asynchronous code, then we pass that code as a callback to the asynchronous code.

Once we have the result of the asynchronous code, the callback is then executed (not immediately though). This is because it is executed only after the call stack is empty.

Now, we have 2 of our issues resolved successfully:-

  • The problem of asynchronous code

  • The problem of dependent code (solved using callback)

Now, consider this situation:-

  • There is a function that performs an asynchronous task.

  • It takes a callback that processes the information received from this call (This too is asynchronous).

  • This callback in turn takes another callback and this continues a few more times.

The structure would look something like this:-

Do you notice this ugly structure? This is called Callback Hell.

This kind of code is very difficult to read and debug. In larger projects, it may get bigger making it even worse. Hence, we shifted to a better programming approach which we will discuss in the next article.

That is all for this article.

I hope you found it insightful.

Kindly let us know your thoughts on it in the comments :)