Rahul Gaba

I am a full stack developer who loves writing code for a living. I am passionate about JavaScript, VR, react-native, nodeJS, web development and Paneer.

Navigation
 » Blogs
 » About Me
 » Projects and Experiments
 » Github
 » XML Feed

Using Async/Await in JavaScript - Writing async code as if it is synchronous

02 Jul 2016 »

Intro


I recently came across the async/await feature of javascript in a meet-up and was blown away after knowing its power.

What is async/await?


Its nothing but a simple and easy to understand approach towards the handling the asynchronous events(callbacks/promises) in javascript.

We all have heard of the callback hell in JavaScript (If you have not heard of it, have a look at callbackhell.com). Then promises came into picture. Promises are great and very easy to manage. But still people do get in trouble while handling promises. Async/Await can be used to handle promises.

Why use async/await?


What if I tell you that you can write your async code as if it was synchronous. That would be awesome right? Well that's exactly what async/await do, obviously without blocking the javascript main thread.

How to use async/await?


It will be easier to show you using an example

We will start with mocking an API response using setTimeout method.


function getResponse() {
let promise = new Promise(function(resolve, reject) {
window.setTimeout(function() {
resolve('done!');
},2000);
});
return promise;
}

Now, the conventional way of Handling this promise would be something like this:


getResponse().then(function(done) {
console.log('response from promise');
});

We will do the same using Async/Await now.


async function logResponse() {
let awaitedResponse = await getResponse(); // awaitedResponse will get the value
//only after the promise in getResponse() gets resolved.

console.log('awaitedResponse is ',awaitedResponse);
}

logResponse();
console.log('Do everything else');

As you just saw, it is working like any normal function and the code works like a synchronous code.


Also note that the code is non-blocking. The thread will print 'Do everything else' before printing the response.


And the best part is that you can use a non-promise value in await too.


eg: you could do the following inside an async function: 


let awaitedResponse = await 'some value';

and the will work just fine.



Verdict


The code looks much more readable and manageable now.

Do have a look at rossboucher.com/await to know more about Async/Await