{{announcement.body}}
{{announcement.title}}

Synchronous vs Asynchronous Programming

DZone 's Guide to

Synchronous vs Asynchronous Programming

In this article, we will discuss What Synchronous Programming is? What Asynchronous Programming is? And whether JavaScript is Synchronous or Asynchronous?

· Web Dev Zone ·
Free Resource

Introduction

In this article, we will discuss What Synchronous Programming is? What Asynchronous Programming is? And whether JavaScript is Synchronous or Asynchronous?

Many developers struggle to understand topics like Callbacks, Promises, and Async/Await, one of the reasons may be not understanding the actual need and core logic behind them.

Having a good grasp of this topic can help you understand them more easily.

Example

This can be better explained with the help of an example.
Imagine you gave your friend a set of tasks:

  • Get Video Games from adjacent towns (somewhere far).
  • Get Chocolate from a nearby store.

What your friend now does is, he first completes task one and head to an adjacent town, and let’s say that takes x amount of time. Then he comes back to you, gives you video games, and then goes to perform the second task, and let’s say it takes y amount of time. The total time taken is x+y. This was just a couple of tasks but imagine there are hundreds of them, the total time is taken increases rapidly if he is a single person doing all the tasks one by one in the order they are given.

The scenario above discussed is how JavaScript runs its code by default, it goes line by line performing each task one at a time before moving on to another one, which means that for the last task or command in the code to run, all the code above it should be executed first. JavaScript's code is executed in a single thread and if a function was to take some time to finish it would freeze everything else in the meantime. Executing one thing at a time is nothing but Synchronous.

By default, JavaScript is a synchronous, blocking, single-threaded language. This simply means only one operation will be in progress at a time. Windows alert function is a good example like,alert("Hello World") when this function is executed whole web page is stuck and you can't interact with it until you dismiss the alert.

Problem

Being Synchronous all the time can be harmful too, as discussed in the above example, if there were a lot of time-consuming lines of code, your application will become much slower. A synchronous IO call blocks the entire thread and JavaScript is single-threaded. Let’s see what this means.

console.log("Start")
 
 for (let i = 0; i < 20; i++) {
   console.log(i)
 }
 console.log("End")

Here is the output of the above code

Start
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
End

As you can see in the result End is not logged in the console until the execution of the loop is finished, this was rather a small loop, imagine if it was i<2000 rather than 20, you could see how much time-consuming it can become. This becomes a very serious problem when you are working on a big application with a lot of server requests.

Solution

So, how should it be solved, the answer is Asynchronous Model of Programming, which means that you can execute multiple things at a time and you don’t have to wait for the current thing to finish before moving on to next one. JavaScript can be manipulated to behave in an Asynchronous way, this is the reason by default was used in the above lines.

And this is where Async/Await, Promises, and Callbacks come into play, they are used to make by default Synchronous JavaScript code to Asynchronous.

Let’s first understand the Asynchronous Model a little more, in the above example, imagine you now have two friends to perform the same task. So, now both of them perform at the same time which leads to total time taken to x (which was supposed to longest of both the tasks). Life becomes much easier when you have more friends to help you, it may seem not much time is saved with just two tasks but again there can hundreds of them.

So in a nutshell, JavaScript just became Multi-Threaded with the ability to perform multiple tasks simultaneously. This changes our definition to JavaScript is an asynchronous, non-blocking, multi-threaded language.

Wait for a second, so there are two definitions, which one is correct? *The answer is JavaScript is a little bit of both of them.

What happens when JavaScript encounters an Asynchronous line of code?

As you all know JavaScript code is executed by JavaScript Engines like V8, SpiderMonkey, Rhino, KJS, Chakra, etc. All these engines have Web APIs that are responsible for handling the asynchronous code in the background. The call stack recognizes functions like Async/Await, setTimeout()etc of the Web API, and they are passed to be handled by the browser. Once those tasks are finished by the browser, they return and are pushed onto the stack as a callback.

The best way to demonstrate this would be using setTimeout() which delays the execution of a function, the first argument is the function( know as a callback function) and the other is the time in milliseconds.

Let’ see an example

console.log("Start")
 
setTimeout(()=>{
 console.log("Middle")
 }, 1000)
 
 console.log("End") 
 // Output of the above code
Start
End
Middle

Let’s break it out line by line.

console.log("Start") is first on the stack, so it gets logged. Next, the JavaScript engine notices,setTimeout() which isn't handled by JavaScript, and sends it to the Web API to be done asynchronously.

The call stack moves on without caring about the code handed off to the Web APIs and console.log("End") is printed.

The setTimeout() the function makes the operation asynchronous by making the Middle to occur after some delay, 1 second. The whole operation doesn't pause for 1 second so it can log Middle, rather it goes on to the next task, logging End.

Even if the time interval is changed to zero seconds, it will still be handled by the Web API’s and will be logged after End.

This way of skipping asynchronous code block to be handled in the background and move forward to the next line of code without blocking the execution of code makes JavaScript Non-Blocking.

Conclusion

In this article, you learned about the Synchronous and Asynchronous Model of Programming and now you understand the need and use of Async/Await, Promises, and Asynchronous Callbacks.

Topics:
async, async asynchronous, javascript, javascript developers, single thread execution, synchronous

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}