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 ES6 and it basically allows you to write asynchronous code in a synchronous way.
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.
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.
Let's see how we implement promises :
let promiseEx = new Promise((resolve, reject) => {
let a = 1;
let b = 2;
let sum = a + b;
if(sum === 3){
resolve("Success")
}else{
reject("Failure")
}
})
Here promiseEx 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.
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 :
const 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
const getData = async () =>{
try{
const result = await fetch("htttps://fetchsomedatafromtheserver.com/data")
console.log(result)
}catch(error){
console.log(error)
}
}
getData()
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.