Async/Await In Javascript For Dummies

Async/Await is a new way of writing asynchronous code in javascript. Before getting familiar with Async/Await lets understand some basics, as this article is targeted for complete beginners.

What does Synchronous & Asynchronous mean?

Ok. Lets get this straight with help of a very simple example.

console.log('Application Started');
console.log('Application Ended');

//Output:
//Application Started
//Application Ended

The above script is an example of synchronous execution, meaning the statement one executes first and then the next statement is executed.

setTimeout(()=>{ console.log('Application Started'); },100);
console.log('Application Ended');

//Output:
//Application Ended
//Application Started

In this example the script is asynchronous in nature, that is the statement two doesn’t wait for the statement one to get completed rather statement two will be executed first followed by statement one.

It’s always preferred to have an asynchronous operation as it increases user experience, think of a scenario where you need to fetch list of movies and to render it in the UI. If running synchronous, the control flow will be blocked till the movie list is fetched, instead we can fetch it concurrently and do other operations which will improve performance of the application

//Synchronous Application

//Suppose this takes 1s to complete
var movieList = FetchMovies(); 

//We have to wait for extra 1s to perform other operations
DoOtherOperations();
//Asynchronous Application

//Suppose this takes 1s to complete
var movieList = FetchMoviesAsync();

//This is done async so we don't have that 1s overhead
DoOtherOperations();


Async code using Javascript Promises:

Promises are objects that may return a value of an asynchronous operation at some point in future. So that the code doesn’t have to wait until an operation is being completed.

Syntax:
new Promise( function(resolve, reject) { … } );

Consider a function to return the list of movies after a specific time as below. We don’t have to wait till we get the response, rather proceed with other operations. Once the promise is resolved (.then()) then we can render the list in UI.

function GetMovieList()
  {
    var promise = new Promise((resolve,reject) =>
    {
     setTimeout(
       resolve([
         {'Id': 1, 'MovieName': 'Dhoom 2' },
         {'Id': 2, 'MovieName': 'Speed' }
       ]), 1000
     );
    });
    return promise;
}

//Fetches the list of movies (Takes 1 Sec)
var movieList = GetMovieList();

//Only after the movie list is returned
//this statement is executed.
movieList.then(function(){
console.log('Render the movies in UI');
});

//This statement is asynchronous and will be executed
//before the movie list is fetched.
console.log('Do other operations'); 

//Output:
// Do other operations
// Render the movies in UI

If there are two operations to be done, where the second operation has to be done after the first. then it may look similar to,


function GetMovieList()
{
 var promise = new Promise((resolve,reject) =>
  {
    setTimeout(
      resolve([
       {'Id': 1, 'MovieName': 'Dhoom 2' },
       {'Id': 2, 'MovieName': 'Speed' }
       ]), 1000
      );
  });
 return promise;
}

function GetMovieReviews()
{
  var promise = new Promise((resolve,reject) =>
   {
     setTimeout(
       resolve([
        {'Id': 1, 'Rating': '4.5' },
        {'Id': 2, 'Rating': '3' }
        ]), 1000
       );
   });
  return promise;
}

GetMovieList().then(
 GetMovieReviews().then(function RenderInUI()
  {
    console.log('Render the movie list and rating');
  })
);

In the above example GetMovieList() is executed first only after its promise gets resolved GetMovieReviews() is executed and so on. The downside of chaining the promises is that it makes the code hard to read as the number of synchronous operation increases.

Now we would have got a general overview of what promises are, to read more about promises and its states click here.

Switching From Promises to Async/Await:

Async/Await helps with managing the flow control in javascript, making the code look synchronous but doing asynchronous operations.

Syntax:
async function name(…param) {
//statements
}

Let’s rewrite the same example given above with the help of Async/Await and see how it looks,


function GetMovieList()
{
 var promise = new Promise((resolve,reject) =>
  {
    setTimeout(
      resolve([
       {'Id': 1, 'MovieName': 'Dhoom 2' },
       {'Id': 2, 'MovieName': 'Speed' }
       ]), 1000
      );
  });
 return promise;
}

function GetMovieReviews()
{
 var promise = new Promise((resolve,reject) =>
  {
    setTimeout(
      resolve([
       {'Id': 1, 'Rating': '4.5' },
       {'Id': 2, 'Rating': '3' }
       ]), 1000
      );
  });
 return promise;
}

async function Init()
{
   var movieList = await GetMovieList();
   //Waits for the previous statement to be executed first
   var reviews = await GetMovieReviews();
   //Waits for the previous statement to be executed first
   console.log('Render the movie list and rating');
}

Init();

You can make a function async by simply adding async keyword before the function declaration, An async function will always use a promise object to return its result. The advantage of async function is that the syntax looks just like a synchronous code.

async function may contain await keyword, that blocks the next statement of the function to be executed till the promise gets resolved/rejected. await keyword can be used only within an async function, using it outside will cause a syntax error.

Thanks for reading, I hope this article has given you a basic understanding on how async/await works. I will write about error handling in async functions on my next post.

If you have any queries or require any further clarification, please comment below.

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s