Sign in
Log inSign up

Async and Await

Suman Ghosh's photo
Suman Ghosh
·Jul 9, 2021·

5 min read

Async and Await

Hi everyone, this is my first ever blog. In this blog I will try to explain async and await in a simple way. This blog will mainly focus on what really is async and await and how to use it.

What is Async and Await ?

Async/Await is basically an extension to promises in Javascript. It acts as a syntactical sugar wrapped around making promises which makes it easier to work with. Using async/await helps developers to read the code in a synchronous way, which allows to keep a better track of what's happening in our code at a given point of time. It is a new feature added to JavaScript in ES8 and it basically allows you to write asynchronous code in a synchronous way.

Getting started

This blog is basically divided into three segments:

  1. How Javascript works.
  2. Promises.
  3. Async/Await.

1. How Javascript works

Before we dive deep into async/await, let's first get a brief understanding of how exactly javascript works. As we all know that javascript executes the code in a synchronous way meaning it runs one piece of code at a time and waits for that piece of code to complete before it moves to the next line. This may sound interesting but in real scenarios it can bring a lot of problems.

The main disadvantage of synchronous way of executing the code is that it blocks the code until it has finished what it's doing. For a long running Javascript functions, it can block the UI until that function is returned and thus results in a terrible user experience.

Suppose if you have a web application, that makes a request to the server for fetching certain data which you would use in your web application. We know that our code is running synchronously so our web page might stop working until it has retrieved data from the server. It also depends on our connection, so for a user having poor connection it might take a lot of extra time and in that meantime the user will not be able to interact with your application.

To solve this issue Javascript has a way of executing the code in an asynchronous manner through the use of Web API's. One of the commonly used Web API is the fetch API where we fetch some data from the server. This Web API's runs the code in asynchronous way by returning a Promise. Now let's look at what exactly is a Promise.

2. Promise

A Promise in Javascript is just like promise in real life. Promise is an object in javascript which has three states pending, fulfilled and rejected. pending is the initial state neither fulfilled nor rejected, fulfilled meaning that the task was completed successfully and rejected meaning that the task failed.

Below is a code snippet of how Promise is written :

let promiseVariable = new Promise((resolve, reject) => {
   let first = 1;
   let second = 2;
   let sum  = first + second;
   if(sum === 3){
      resolve("Success")
   }else{
      reject("Failure")
}
})

Here promiseVariable is a promise which on successful completion resolves the request and on failure rejects the request. This code is addition of two numbers and if the sum of both the numbers is 3 then it will resolve or else will reject the request.

The promise promiseVariable is called like this :

promiseVariable.then((message) => {
    console.log("In the then block", +message)
}).catch((message) => {
    console.log("In the catch block", +message)
})

Then .then block is going to be called when promise is resoled successfully and .catch is called when the promise is rejected.

Now that we know the basics of Promises, let's go ahead to the last segment of this blog.

3. Async/Await

To give you all a clear understanding of async and await lets take an example of fetching data from the server using fetch API. First I will write the code using promise and then later modify with async and await.

Fetch data using promise :

function getData(){
    fetch("htttps://fetchsomedatafromtheserver.com/data")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error))
}
getData()

In the code above it is making request to fetchsomedatafromtheserver api. This returns an array of data. On the second line it is making a HTTP request which returns a promise. If the promise is successful it will proceed to the first then on third line and later to the next then whereas if at any given point the promise is unsuccessful or rejected then it will go to the catch block and console.log the error.

Now lets modify the above code using async/await

async function getData(){
  try{
    const result = await fetch("htttps://fetchsomedatafromtheserver.com/data")
    console.log(result)
  }catch(error){
    console.log(error)
  }
}
getData()

Lets walk you through the code.

The first step to while using async/await is to make the javascript interpreter know that this piece of code or this function will run in an asynchronous way. This is done by writing the keyword async in front of the function. In async/await the errors are handled using the try/catch block. The try/catch block runs the same way like .then and .catch. In try block all the important functionalities are written.

The next important keyword is the await keyword on line 3. Once Javascript hits this await keyword it will move out of that function, do all the other task that are there in the program. As soon as the fetch has completed executing the request it would return the result in the result variable and later will console.log the result in the next line.

If you look at both the code snippet then you might think that async/await has more lines of code because of using try/catch but async/await really help us reading the code in a synchronous way. The example I took to explain is a very simple one, but asynchronous code can get a lot more complex and that is when async/await is the most effective solution.

Thanks for reading my first ever blog. I hope you liked and it has given you a better understanding of async/await. Do let me know your feedbacks on the comments section.

Have a good day :)

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct