Asynchronous JavaScript – Callbacks, Promises, and Async/Await explained

If you’ve been learning JavaScript for a while, you’ve probably heard the term “async” before.

This is because JavaScript is an asynchronous language…but what does it mean exactly? In this article, I hope to show you that this concept is not as difficult as it sounds.

Synchronous and Asynchronous

Before we get into the real deal, let’s look at the two words – synchronous and asynchronous.

By default, JavaScript is a synchronous, single-threaded programming language. This means that instructions can only be run one after the other, not in parallel. Consider the following small code snippet:

 let a = 1 ; let b = 2 ; let sum = a + b ; console . log ( sum ) ;

The code above is very simple – it adds two numbers and logs the sum to the browser console. The interpreter executes these instructions one after the other in this order until it completes.

But this approach also has drawbacks. Suppose we want to fetch a large amount of data from a database and display it on our interface. When the interpreter reaches the instruction to fetch this data, the rest of the code is blocked from executing until the data is fetched and returned.

Now you might say that the data to be fetched is not that big, and it won’t take any noticeable time. Imagine you have to fetch data at many different points. This kind of delayed compounding doesn’t sound like something users want to experience.

Luckily for us, synchronization was solved with the introduction of asynchronous JavaScript

The post Asynchronous JavaScript – Callbacks, Promises and Async/Await explained first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/9832
This site is for inclusion only, and the copyright belongs to the original author.