Programming asynchronously: Async Await

One of the big issues with using either callbacks or Promises is that the code becomes much more complex that it would, if you were using a synchronous programming language. This is where async and await comes in. The keywords are borrowed from C# and .NET and is without doubt one of my favorite features of using C#.
You need to prefix your function with the “async” keyword before you can use the await keyword. And every async method will return a promise.
This means that you could make a promise by making a async method and use return and throw instead of a regular promise with resolve and reject.
So, you’re inside a async method and want to fetch some data from a method that returns a promise; either a promise or another async method. You could either use .then() like before or you could just do something like this:

Look at the full example below:

I think that async / await in general makes code less complex, because you can hide most of the callback / promise stuff behind the await keyword, and treat it more like a regular program in for example Python or Ruby. But remember that every method that uses await, need to be async; this means that you need to do this “hack”: await Promise.all( d => d*2)) hack if you need to do await inside a map. Because the map code will return an array of promises. Like I said, all async methods returns a promise. Then, you can resolve them using promise all, and if you prefix it with await, it will give you the result of all of them in an array as result.
Again, Promises and Async methods are two sides of the same coin. I personally look at Promises as the technology behind it all, and mostly use async await to make and deal with them.

Arif Khoja
Arif Khoja is a Developer. He is a Javascript Enthusiatic who loves logical programming and has first hand experience in building a cutting edge internet product using Angular. He is also an open source freak and keen about learning and sharing. He writes Javascript both frontend and backend. He loves learning and sharing tech all the time. He also has a hands on experience in SEO and writes articles about latest emerging technologies.
Arif Khoja on FacebookArif Khoja on GoogleArif Khoja on InstagramArif Khoja on LinkedinArif Khoja on Twitter

Leave a Reply

%d bloggers like this: