Asynchronous JavaScript

Asynchronous JavaScript

Lets understand Async JavaScript in a simple way!

To understand Async JavaScript in a simple way lets go through some examples.

var age = "Twenty"
console.log(age)

// output : Twenty
var age = "Twenty"
console.log(age)
age = "Twenty-One"
console.log(age)

//output : 
//Twenty
//Twenty-One

In the above code snippets, as we have seen earlier JavaScript Behind the Scenes. So, Javascript runs all the lines of code synchronously and gives the desired output. But, this is not going to work in all scenarios. Lets take a look at those situation where synchronous javascript is not going to work.

Use case of Asynchronous JavaScript

The most common situation is While we use APIs to fetch data from the endpoints. Now the time required to fetch data from the APIs depends on various parameters like Internet Speed, Size of the data requested etc. So, we have to wait till the response comes from the API and then run the lines of code written after that. So, In order to do that, Asynchronous JavaScript comes into picture.

Promises

To implement async javascript, the first thing that comes into mind is Promises. the promises are built in objects in javascript to do stuff like waiting for response etc. However, we do not have to specifically write some method to wait. lets look at an example for this

const axios = require("axios")

const getData = () => {
    const data = axios.get("https://jsonplaceholder.typicode.com/posts")
    data
    .then((res) => {
      console.log(res)
    })
    .catch((err) => {
      console.log(err)
    })
  }

getData();

In above code, then and catch are built in methods chained on the promise such that they are not called till the data is not received from the API. in .then() method, we can write our functions/code to display or update the received data by passing that data as an argument to our function. .catch() method is used to return the error occured when it fails to receive the data from server. So, this is how Promises work.

Async-Await

Now, To write the Promises more easily and conveniently the Async and Await keywords were introduced. The keyword Async is used to make function behave as Asynchronous & return a Promise and Await is used to wait till the promise is returned. lets write the above code again using Async-Await and see how it is implemented.

const axios = require("axios")

const getData = async () => {
    try{
     const data = await axios.get("https://jsonplaceholder.typicode.com/posts");
     console.log(data)
     }
     catch(err){
     console.log(err)
     }
}

getData();

So, this is how async-await is implemented. For error handling, normal try-catch block is used and we receive the data in the console.