DEV Community

Cover image for Asynchronous JavaScript ๐Ÿ”ฅ๐Ÿ˜Ž
Shaik Dawood
Shaik Dawood

Posted on • Edited on

Asynchronous JavaScript ๐Ÿ”ฅ๐Ÿ˜Ž

Hello everyone,๐Ÿ‘‹
If you are new to JavaScript, it can be little bit of challenging to understand its async nature๐Ÿคทโ€โ™‚๏ธ. But don't worry keep your fingers crossed๐Ÿคž because in this article you'll get full information regarding asynchronous JS๐Ÿ˜.

To understand asynchronous JavaScript, firstly we need to understand what is Synchronous JavaScript๐Ÿค”. The term Synchronous defines the only one task can be done at a time. So in JavaScript, in a particular block of code the lines ate executed one by one. While each operation is being processed, nothing else can happens because the rendering is paused๐Ÿฅด. This happens because the JavaScript is a single threaded language, only one thing can happen at a time on single main thread and everything else is blocked until an operation completes.

โšกSo, in simple terms the Asynchronous JavaScript is Start something now and finish it later. So it governs how we perform the tasks which takes some time to complete. Many Web API features now use asynchronous code to run, especially those that access or fetch some kind of resource from an external device, such as fetching a file from the network, accessing a database and returning data from it.

Still confusing why we need Asynchronous ??๐Ÿค. Let's look at the following Image to get a clarity.

async

Alright folks, now we know that how asynchronous code works right. Let's head over to another topic.

โšกHTTP Requests: We generally used to make the HTTP requests to get the data from another server. We make these requests to API Endpoints.
๐ŸŒˆLook at the following Image.

Http

Most of the data is grabbed in the JSON Format.
Wondering how to make the HTTP request?. Observe the following code:

http req

Now we got to know that how to make request right. But how do we access the response data?๐Ÿค”. Well in our code we can track the progress of request using an Event Listener and a specific event called readystatechange . Let's implement that in our code.

http im

So by using this code we can make a HTTP request.๐Ÿคœ๐Ÿค›
Sounds Overwhelming ?? ๐Ÿคทโ€โ™‚๏ธ Well hold on there's lot more to go.โœŒ

Let's move on to the next topic:

โšกCallbacks:
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of task.๐ŸŒˆ

Let's look at the example code below.

callbacks

However, that callbacks are often used to continue code execution after an asynchronous operation has completed โ€” these are called Asynchronous Callbacks. A good example is the callback functions executed inside a ".then()" block chained onto the end of a promise after that promise fulfills or rejects. This structure is used in many modern web APIs, such as "fetch()".
โšกDefinition of Async Callback: The Asynchronous Callbacks are the functions that are specified as arguments when calling a function which will start executing code in the background. The best example for Async Callback is the Second Parameter of the .addEventListener .

Let's deep dive into some more topics now.

โšกPromises:

๐Ÿ‘‰Def: A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.
Sounds tedious right?๐Ÿฅด. Well don't worry let's understand it in simple way.

  • โšก๐Ÿ‘‰"Producing Code" is code that can take some time.
  • โšก๐Ÿ‘‰"Consuming Code" is code that must wait for the result.
  • โšกโšก A promise is a JavaScript object that links Producing code and consuming Code.

So Technically a promise is simply an object in JavaScript. A promise is always in one of the three states:

  • โžก๏ธ pending: which is initial state, neither fulfilled nor rejected
  • โžก๏ธ fulfilled: meaning that the operation completed successfully.
  • โžก๏ธ rejected: meaning that the operation failed. So basically we cannot access the properties state and results, we must use promise method to handle promises.

How to implement that is shown below:

promise

Now why we need Promises?๐Ÿค”

Promises help us to deal with asynchronous code in a far more simpler way compared to callbacks.
Callback hell can be avoided with Promises.

Look at the below image to get a idea about Promises.

Promise

Let's jump into another topic:

โšกAsync / Await: Async and await make promises easier to write.

  • Async makes a function return a promise.
  • Await makes a function wait for a promise.

The await keyword can only be used inside an Async Function. Async / await is another way of handling promises in JavaScript. One of the main advantage of using it is clean code.
In general, we use .then().catch() to handle promises right, but now let's handle it using async / await. We can write using function statement or function expression. Both will be valid, only difference is use of anonymous function in function expression.

async

To handle error in async await, we can use 'try and catch'

Look at the code below for the same:

async err

Conclusion:

The web browsers define functions and APIs that allow us to register functions that should not be executed synchronously, and should instead be invoked asynchronously when some kind of event occurs. If we're running an operation that takes time however, like querying a database and using the results to populate templates, it is better to push this off the stack and complete the task asynchronously. Over time, you'll learn when it makes more sense to choose an asynchronous technique over a synchronous one.

See you in next article. Goodbye ๐Ÿ–.

Top comments (0)