Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Follow publication

But what is Synchronous and Asynchronous programming?

Callbacks, Promises, and Async-Awaits…. What are these and why do we even need them? If you are a newbie it is pretty easy to get confused by these terms. So let's end this confusion once and for all and break this into small, easier-to grasp concepts.

Let’s start with figuring out what Synchronous and Asynchronous programming is.

Synchronous programming

Source: https://medium.com/from-the-scratch/wtf-is-synchronous-and-asynchronous-1a75afd039df

In synchronous programs tasks are performed one at a time and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one.

console.log("Hello,") //Instruction 1const syncExample=()=>{console.log("How are you?") }syncExample()//Instruction 2console.log("World.")//Instruction 3

Since javascript is a single-threaded programming language i.e. it reads code line by line and executes them in that order, the output for the above Synchronous code snippet is as follows.

Hello,
How are you?
World.

As expected by the javascript compiler, Instruction 1 is read and executed first, then Instruction 2 and Instruction 3.

Asynchronous programming

Asynchronous programming allows you to perform parallel programming. That way you can perform that work without blocking the main process/thread.

In the following code snippet, I have modified our previous code and made it asynchronous by adding the operation setTimeout. There are several asynchronous functions like ClickListener, fetch, setInterval, etc. that can be used as well.

console.log("Hello,"); //Instruction 1const asyncExample = () => {setTimeout(() => {console.log("How are you?");}, 3000);};asyncExample(); //Instruction 2console.log("World."); //Instruction 3

Can you guess the output for the above? From what we know about javascript behavior, Instruction 1 should execute first, then after waiting for 3 seconds instruction 2, and then finally instruction 3. Right?

Not quite. The actual output is as follows.

Hello,
World.
How are you?

So what is happening here? Why is javascript misbehaving?

Actually, it’s not.

Javascript simply sends its asynchronous operations to a WebAPI and in turn, the WebAPI keeps track of the timer in the setTimeout function. So basically when the JavaScript compiler encounters the asynchronous function it simply pops off that execution context to the WebAPI and continues with its main function. Thus performing two tasks simultaneously.

Source: https://www.dotnetcurry.com/aspnet/1192/aspnet-web-api-async-calls-mvc-wpf

But what if we want the result of an asynchronous function in our main execution context? That is where the problem arises.

Let me show you an example.

console.log("Hello,"); //Instruction 1const asyncExample = (givenName) => {setTimeout(() => {console.log("Execution of function.");return { name: givenName };}, 3000);};console.log(asyncExample("Puja")); //Instruction 2console.log("World."); //Instruction 3

Due to the setTimeout function, the asyncExample returns its output after 3 seconds of execution. The output for the above code snippet is

Hello,
undefined
World.
Execution of function.

As the asyncExample function was still underway when it was called, the compiler returns an ‘undefined’ output. Finally, when the setTimeout function is done running, we get the console log output “Execution of function.” inside the asyncExample function. There are several ways to solve this problem by allowing the asynchronous function to complete its execution and then retrieveing the data in a function call.

In my next article, I will discuss callback, promises, and async-await that helps deal with the problem with asynchronous code.

Hello, hope you liked the article. I am Puja, a developer in the making. It takes a lot of work to research for and write such an article, and a clap or a follow 👏 from you means the entire world 🌍to me. It takes less than 10 seconds for you, and it helps me with reach! You can also ask me any questions, or point out anything, or just drop a “Hey” 👇 down there.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Puja Chaudhury
Puja Chaudhury

Written by Puja Chaudhury

Masters' student in Robotics focusing on machine learning. Experienced in AI, NLP, and CV through internships, research projects, & published papers.

No responses yet

Write a response