Understanding async-await in Javascript – Hacker Noon

Async and Await are extensions of promises. So if you are not clear about the basics of promises please get comfortable with promises before reading further. You can read my post on Understanding Promises in Javascript.

I am sure that many of you would be using async and await already. But I think it deserves a little more attention. Here is a small test : If you can’t spot the problem with the below code then read on.

We will revisit the above code block later, once we have gone through async await basics. Like always Mozilla docs is your friend. Especially checkout the definitions.

async and await

From MDN

An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.

I wonder who writes these descriptions. They are so concise and well articulated. To break it down.

The function operates asynchronously via event loop.

It uses an implicit Promise to return the result.

The syntax and structure of the code is similar to writing synchronous functions.

And MDN goes on to say

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise‘s resolution, and then resumes the async function’s execution and returns the resolved value. Remember, the await keyword is only valid inside async functions.

Let us jump into code to understand this better. We will reuse the three function we used for understanding promises here as well.

A function that returns a promise which resolves or rejects after n number of seconds.

There is a lot of unnecessary code here like anonymous function just for assigning the handlers. What async await does is it improves the syntax for this which would make seem more like synchronous code. If we had to the same as above in async await format it would be like

result = await promiseTRSANSG(3);console.log(result);

Well that look much more readable than the standard promise syntax. When we used await the execution of the code was blocked. That is the reason that you had the value of the promise resolution in the variable result. As you can make out from the above code sample, instead of the .then part the result is assigned to the variable directly when you use await You can also make out that the .catch part is not present here. That is because that is handled using try catch error handling. So instead of using promiseTRSANS let us use promiseTRRARNOSG Since this function can either resolve or reject we need to handle both the scenarios. In the above code we just wrote two lines to give you an easy comparison between the standard format and async await format. The example in next section gives you a better idea of the format and structure.

From the above code example you can make out that instead of using the promise specific error handling we are using the more generic approach of using trycatch for error handling. So that is one thing less for us to remember and it also improves the overall readability even after considering the try catch block around our code. So based on the level of error handling you need you can add any number of catch blocks and make the error messages more specific and meaningful.

Pitfalls of using async and await

async await makes it much more easier to use promises. Developers from synchronous programming background will feel at home while using async and await. This should also alert us, as this also means that we are moving towards a more synchronous approach if we don’t keep a watch.

The whole point of javascript/nodejs is to think asynchronous by default and not an after though. async await generally means you are doing things in sequential way. So make a conscious decision whenever you want to use to async await.

Now let us start analysing the code that I flashed at your face in the beginning.

This seems like a harmless piece of code that fetches the github details of three users “nkgokul”, “BrendanEich”, “gaearon” Right. That is true. That is what this function does. But it also has some unintended consequences.

As you can find from the output, each of the await function is called after the previous function was completed. We are trying to fetch the details of three different users“nkgokul”, “BrendanEich”, “gaearon” It is pretty obvious that output of one API call is in noway dependent on the output of the others.

We can create the userDetailsJSON object only after getting the userDetails. Hence it makes sense to use await here that is within the scope of getting the details of a single user. So let us make an async for getting the details of the single user.

As you can make out from the output, promise creations are almost instantaneous whereas API calls take some time. We need to stress this as time taken for promises creation and processing is trivial when compared to IO operations. So while choosing a promise library it makes more sense to choose a library that is feature rich and has better dev experience. Since we are using Promise.all all the API calls were run in parallel. Each API is taking almost 0.88 seconds. But since they are called in parallel we were able to get the results of all API calls in 0.89 seconds.

In most of the scenarios understanding this much should serve us well. You can skip to Thumb Rules section. But if you want to dig deeper read on.

Digging deeper into await

For this let us pretty much limit ourselves to promiseTRSANSG function. The outcome of this function is more deterministic and will help us identify the differences.

Concurrent Start of Execution

asynchronous execution starts as soon as the promise is created. await just blocks the code within the async function until the promise is resolved. Let us create a function which will help us clearly understand this.

From previous post we know that .then is even driven. That is .then is executed as soon as the promise is resolved. So let us use resolveAfter3seconds.thenand resolveAfter4seconds.then to identify when our promises are actually resolved. From the output we can see that resolveAfter3seconds is resolved after 3 seconds and resolveAfter4seconds is executed after 4 seconds. This is as expected.

As we have seen from the output of .thenresolveAfter3seconds resolved one second before resolveAfter4seconds . But we have the await for resolveAfter4seconds and then followed by await for resolveAfter3seconds

From the output we can see that though resolveAfter3seconds was already resolved it got printed only after the output of console.log(await resolveAfter4seconds); was printed. Which reiterates what we had said earlier. await only blocks the execution of next lines of code in async function and doesn’t affect the promise execution.

Disclaimer

MDN documentation mentions that Promise.all is still serial and using .then is truly parallel. I have not been able to understand the difference and would love to hear back if anybody has figured out their heard around the difference.

Thumb Rules

Here are a list of thumb rules I use to keep my head sane around using async and await

aync functions returns a promise.

async functions use an implicit Promise to return its result. Even if you don’t return a promise explicitly async function makes sure that your code is passed through a promise.

await blocks the code execution within the async function, of which it(await statement) is a part.

There can be multiple await statements within a single async function.

When using async await make sure to use try catch for error handling.

If your code contains blocking code it is better to make it an async function. By doing this you are making sure that somebody else can use your function asynchronously.

By making async functions out of blocking code, you are enabling the user who will call your function to decide on the level of asynhronicity he wants.

Be extra careful when using await within loops and iterators. You might fall into the trap of writing sequentially executing code when it could have been easily done in parallel.

await is always for a single promise. If you want to await multiple promises(Run this promises in parallel) create an array of promises and then pass it to the Promise.all function.

Promise creation starts the execution of asynchronous functionality.

await only blocks the code execution within the async function. It only makes sure that next line is executed when the promise resolves. So if an asynchronous activity has already started then await will not have an effect on it.

Please point out if I am missing something here or if something can be improved. If you liked this article and would like to read similar articles, don’t forget to clap. There is a limit of 50 claps on medium. Do check it out 😉