Shreyansh Jain
Shreyansh Jain's Blog

Shreyansh Jain's Blog

Javascript | Understanding Synchronous and Asynchronous

Javascript | Understanding Synchronous and Asynchronous

Shreyansh Jain's photo
Shreyansh Jain
ยทMay 3, 2022ยท

4 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

One of the topics that most Javascript developers find difficult to understand is synchronous and asynchronous programming. Believe me, after reading this, you will surely grasp what it is ๐Ÿ™‚ and it will boost your confidence.

Understanding synchronous

Suppose a scenario; you went to a movie hall with your date. (Don't have a date, don't feel bad, we programmers are mostly single ๐Ÿ˜„) Haha, jokes aside, suppose you are in a queue, and it's your turn. From the counter person point of view, these are the steps being followed as depicted in the diagram below.

book_ticket_flow.png

This is what synchronous flow looks like. All the steps listed above can be executed once the previous step is over.

If I was to write the following sequence using javascript, this is how I would write. I haven't added any complex logic to the functions; they are simple and self-explanatory.

function askForMovie() {
  prompt("Which movie you want to book ticket for?");
}
function acceptPayment() {
  console.log("Accepted the required payment for the movie ticket");
}
function bookTicket() {
  console.log("Seats are reserved for the particular movie");
}
function provideTicket(customer_name) {
  console.log(`Tickets are provided to the customer ${customer_name}`);
}
let total_customers = 5;
for(let i = 0; i < total_customers; i++) {
    askForMovie();
    acceptPayment();
    bookTicket();
    provideTicket(i);
}

book_ticket_javascript_implementation.png All the functions are executed one by one. It won't move to the next function until the execution of the current function is complete. This is what synchronous is.

Understanding asynchronous

Consider another scenario. You went to Mc Donalds to order food.

depositphotos_433573032-stock-illustration-queue-fast-food-restaurant-concept.jpg

From a counter person point of view, the series of steps that can be seen are depicted in the diagram below:-

order_food.png

This case is interesting; if you observe here, we don't wait for the food to get prepared before moving on to the next customer; in fact, food is being prepared in the background, and the customer is notified once it is available. We know how bad the service would be if they make the next customer wait until the food is available for the current customer.

The same thing we can observe in programming, there are many cases like fetching API, uploading some data, and performing extensive calculations. If javascript were to wait for the operations to complete, the performance would be seriously affected. So we make use of asynchronous APIs in javascript for this.

Let's implement the above food order scenario using javascript:-

// defining some sample time for items to prepare
let time_needed = {
    "French Fries": 2000,
    "Mc Spicy Paneer": 3000,
    "Iced Coffee": 1000,
    "Big Mac Burger": 4000
}
function takeFoodOrder(customer_no) {
  console.log(`Order is taken for customer ${customer_no}`);
}
function acceptPayment(customer_no) {
  console.log(`Payment is accepted for customer ${customer_no}`);
}
function notifyCustomer(customer_no, item) {
    console.log(`Customer ${customer_no} please take your ${item}`);
}
function prepareFood(customer_no, item) {
    setTimeout(function () {
        console.log(`Food is ready is ready for customer ${customer_no}`);
        notifyCustomer(customer_no, item);
    }, time_needed[item])
}
total_customer = 2;
customer_item = ['French Fries', 'Big Mac Burger'];
for(let i = 0; i < total_customer; i++) {
    takeFoodOrder(i);
    acceptPayment(i);
    prepareFood(i, customer_item[i]);
}

Output Animation:-

ezgif.com-gif-maker.gif

From the animation, we can clearly see that the food order and payment acceptance do not wait for the food preparation to be complete. One more thing to note here is that the notifyCustomer(), although it takes minimal time, is executed after the food preparation is over. This is very important. In asynchronous programming, there are many cases where some functions are dependent on the asynchronous functions/statements. Eg:- printing the data after it has been fetched. Fetching data takes time, and we can't print it until we have processed it successfully, so we use callback functions here. Callback functions are called after the asynchronous statements are done with their execution.

prepareFood() uses the function setTimeout which is asynchronous, which means it happens in the background; the next operation is not blocked because of this. setTimeout is one of the examples of asynchronous APIs that Javascript is using; there are many others like setInterval, fetch, etc. which have their own use cases.

Conclusion

In this blog, I tried to cover what is synchronous and asynchronous programming by comparing with real life examples. Understanding this concept is important before jumping into callbacks, promises, and async/await in detail.

Hope this blog helped you. Please like this post if it was useful to you. ๐Ÿ˜Š

ย 
Share this