Asynchronous javascript: Async /Await

Deepak Jha
TechCret Software
Published in
2 min readJun 7, 2020

In this blog, I will explain to you how we can simplify the promises in a very simple way, and also this is very easy to understand and use.

So we already study in the last blog that promise is a big improvement over callbacks but still, promises can be really hard to read and manage especially when we have a long chain of multiple asynchronous events.

Async and Await is a fine syntactic sugar to make out Asynchronous code to execute like a Synchronous code.

Async

Async with a function just indicates that this function always returns a promise so when we use the async keyword then it takes the return value and automatically resolves it as a promise.

Example

Await

Async set up a context to use the await keyword, the main power of the async function is when we bind it with the await keyword to pause the execution of a function until promise resolve and return its result and this keyword only works inside an async function.

This is very useful when we need one value after another, like if the second statement dependent on previous statement value, for example, if we need user id before fetching his information;

Example

Few points to remember before using Async Await

  1. await can not be used in regular function and if we use then end up with an error.
  2. await will not work in the top-level-code.

Example

Top-level-code

But we can wrap it into an anonymous async function.

Example

--

--