Is Javascript synchronous or asynchronous 🤔 ?
Well before diving straight into the topic, have a look at what they mean 👇.
Synchronous Code: To put it simply, synchronous means to be in a sequence, that is every statement of the code gets executed one by one. Therefore, a statement has to wait for the earlier statement to get executed.
Take a look below👇 :- Here, One thing is happening at a time.
Let us understand with the help of an example.
Example :
Output :
In the above code, each statement has been executed right after another following a sequence.
Asynchronous Code: Asynchronous code allows the program to get executed immediately without blocking the further execution of the remaining code until it finishes the current one (statement). In the beginning, this might not look like a big issue though as we go into depth, we realize that it may cause lagging in the user interface.
Take a look below👇 :- Here, you can see that each image is coming simultaneously, at its own pace. None of them is waiting for any of the others.
Let’s see the example of how Asynchronous Javascript works.
Output :
So, what the code does is first it executed “Hey! I’m here” that rather than implementing the setTimeout function it logs in “I Hope, You are well”, and then it implements the setTimeout function.
So now, as you have a good understanding of synchronous and asynchronous code, thus let’s not confuse a language’s itself with its features.
Javascript has always been synchronous in its behavior. Although, its features, ways of dealing with previous issues using callbacks, promises, async/await allows you to implement asynchronous (behavior) event handling in your project.
Now, Let’s talk about those approaches through which javascript achieves asynchronous behavior:-
(i)Callback functions:- The earliest and most straightforward solution to being stuck in the synchronous world was asynchronous callbacks.
When a function directly accepts another function as an argument, then this contained function is known as a callback function. Callback functions can be named or anonymous. Callback functions have been found as the core functional programming concept even in simple functions like setInterval, event listening or making API calls.
Let us see below an example of callback functions,
Output :
In the above example, we used the .map() method to iterate through the array list, the method accepts a callback function which states how each element of the array are going to be. Callback functions can accept arguments as well.
When multiple functions are created in a function that is used as callback functions, then this creates multi-level functions. When this tree-like function becomes too large, the code becomes incomprehensible sometimes and hard to manipulate. It is known as callback hell.
(ii)Promises:- To deal with callback hell, libraries like Bluebird or Q allowed programmers to clean up their syntax and write code that operated asynchronously but looked synchronous. It resulted in code that was easier to read and faster to run.
I Promise to do this whenever it is true. If it isn’t true, then I won’t.
It is the most common illustration of javascript promises. Sounds like an IF statement? Shortly, we will see a huge difference.
A promise is used to handle the asynchronous result of an operation. Javascript is designed not to wait for a block of an asynchronous code to fully execute before other synchronous parts of that code can run. For instance, when making API requests to servers, we have no idea whether the servers are offline or online, or how long it takes to process the request.
Output :
In the above example, we have used .then() to grab the value when the promise resolves and .catch() when the promise rejects.
Through Promises, we can defer the execution of a code block until an async request is implementing. This way, other operations can keep running without interruption.
There are three states of a Promise :
- Pending: It is the initial state of a Promise before an operation begins.
- Fulfilled: This implies, the specified statement gets executed.
- Rejected: Usually, an error value is thrown because the operation didn’t complete.
(iii)Async/Await:- Promises were fantastic, that ES6 brought them into the language as a standard. Using promises still left asynchronous code looking and feeling slightly wonky, so now we have a much better and stunning Async/Await to help us out!
An async function is a modification to the syntax used in writing promises. We can call it syntactic sugar over promises. It only makes writing promises easier. It returns a promise — if the function returns a value, the promise will be resolved with that value, but if the async function throws an error, then the promise is rejected with that value.
Output :
Although Await is only used with an async function. The await keyword is used in an async function to ensure that all promises returned in the async function are synchronized, ie. they wait for each other.
So, this was all about the synchronous behavior of javascript that makes it look-like asynchronous. The objective of this article is to clear the misconception about javascript.
This would surely bear results. If you loved this, then help others like you, by giving claps 👏👏👇 by promoting this article!