Skip to main content

Command Palette

Search for a command to run...

The Maggi Guide to Synchronous vs. Asynchronous Programming

Let's make some maggi with JavaScript.

Updated
7 min read
The Maggi Guide to Synchronous vs. Asynchronous Programming

Hey there! Welcome Back!

Synchronous and Asynchronous, I don't know why but these two terms feels like sometimes out of the world for many students. But they forgot the most important aspect of it which is, Sync and Async is not some coding syntax. They are basis of your daily working. Unknowingly, you perform these tasks on daily basis. So, relax and just read this, everything will make sense once you finish reading.

Okay, the most common thing which everyone has done, is to make maggie at 2 AM in the morning. Everyone has done it maybe at different places but we all did it. Now, lets me introduce you to Aayush and Tushar, both are roomates but the way they cook maggi perfectly reflects synchronous and asynchronous tasks. Now, notice how they cook the same maggie differently,

Analogy

Aayush ( The Synchronous Chef )

Aayush, enjoys the whole process of cooking for him eating maggie is one thing but its the cooking which makes him happy. He does the cooking following steps,

Firstly, he will place the kettle and pour water and he will wait until the water is boiling. During that time he will not do anything and once the water is boiled then only he will open the packet of maggi and starts cooking. During the cooking too he follows the series of step and every single item has its own process. While this costs him time but he enjoys it.

Result: The whole process took him 10 minutes and in those 10 minutes he was sitting idle for 7 minutes as he waiting for one task to get completed and only after that he begins the other.

In Javascript, we all this as blocked thread. We all know that the JS is a single threaded engine which means that it can perform only one task at a time, the other task has to wait for the task to get completed. If this were a web browser, the screen would be completely frozen—the user couldn't even scroll.

Tushar ( The Asynchronous Chef )

Tushar, doesn't care about cooking. He justs wants to eat his maggie. The first step of tushar is same as aayush he also put the kettle on to boil the water but the difference starts here,

So, he delegates. He lets the kettle do its thing in the background.

He (the main thread) doesn't wait for the water to boil. He just move to the next task to unpacking the maggie, cutting chillies. And once he is done with this, he starts watching his movie. The moment he sees that the water is boiled, he just put the maggie with chillies and leaves it for cooking.

Result: It just took him 6 minutes, as he was doing all the task simultaneously. He didn't wasted time in waiting for a particular task to get complete instead he delegated it to other things which does the job for him.

What is Synchronous Programming?

At its core, synchronous programming means executing the code sequentially, strictly. It means Javascript runs the programming line by line, from top to bottom. It won't move to the second line until it has completely executed the first line.

Pros:

  1. Absolute Predictability: You know exactly the order of things in which the code is gonna execute. You need to worry about, which part of code will execute first and which last?

  2. Debugging: When an error occur on the fourth line, you for sure know that the line one, two and three have no error in them. You just need to debug the fourth line.

Cons:

  1. Thread Blocking: When one thing is executing by the thread no other thing can run on the thread. The thread is blocked until the task has been executed completely.

  2. Resource Wastage: The CPU remains idle for long time when it is waiting for network request or some API call. These deal wastage of mulitple resources.

What is Asynchronous Programming?

Asynchoronous Programming is the art of executing non-blocking code. When we are running some heavy task which we know it is gonna take some time instead of waiting for it to complete, we just hand it over to the background and once the task is complete, the background will tell us that your task has been succesfullly completed. We will learn about this background in the upcoming blog.

Just like tushar, he didn't wait for the kettle to boil water. He moved to other task till the time the kettle was boiling and when the water boiled he moved back to it.

Pros:

  1. Massive Concurrency: This is beauty of Node.js that it allows us to handle multiple task at once. A server can handle millions of request concurrently without crashing.

  2. Responsive UI: When our thread is not blocked, we can easily performed other task in the UI without feeling any lag.

Cons:

  1. Unpredictibity: The code no longer finishes in the exact order. As the background is completing task, the CPU can complete the other task. So, the sequence of execution of code gets broken.

  2. Debugging: Debugging becomes real hard as there is no proper flow of execution of program as task get hand off to the background and back multiple times.

Need of Async in JavaScript

Unlike Java or C++ which has multiple threads which allows them to have parrallel programming, JS is a single-threaded language which means that there is only one CPU which executes the program.

You might be thinking that if there is only one CPU, then how JS visually appears to execute in parrallel programming like Java or C++. Async is the reason behing it.

In reality, there are multiple modules which are build upon the JS engine or they are attached to the engine, which allows the JS to execute task so efficiently. Without the asynchronous programming, we would be stuck at every single step of code execution which delay the speed of the execution or production.

Real World Examples

You rely on asynchronous programming every single time you open an app:

  • API Calls: When you open Swiggy or Zomato, the UI loads instantly, but the restaurant list takes a second to pop up. The app fetches that data asynchronously.

  • Database Queries: Reaching out to a MongoDB database to verify a user's login credentials.

  • File System Operations: Reading or uploading a heavy CSV file on a backend server.

  • Timers: Using setTimeout to show a promotional pop-up 5 seconds after a user visits a page.

Role in MVC Architecture

If you want to transition from a "coder" to a "backend engineer," you must understand how this fits into system design. In the Model-View-Controller (MVC) pattern, asynchronous execution is the backbone of your routing.

Imagine you are building a retail dashboard:

  1. The Controller (The Traffic Cop): A request hits your Express router to view an order. The Controller takes charge. It must be marked as async.

  2. The Model (The Heavy Lifter): The Controller calls a method on the Model (e.g., Order.findById()). This is a slow, I/O database operation.

  3. The Delegation (await): The Controller uses the await keyword. This tells the system: "Pause this specific request and wait for the Model, BUT free up the main thread so the server can handle other users in the meantime."

  4. The View (The Response): Once the database finds the order, the background worker hands it back to the Controller, which then sends the JSON response to the frontend.

If you write a synchronous backend, the moment one user requests a massive database query, every other user on your app is stuck waiting in Aayush's kitchen.

#JavaScript #WebDevelopment #CodingLife #AsyncJS #MERNstack #100DaysOfCode #ProgrammingTips #BackendEngineering

More from this blog

Web Devlopment Journey

48 posts

In this publication, you will find articles related to web devlopment whether it be git or node.js. There will be blogs on every single topic and more will be coming soon...