Async/await

As JavaScript is asynchronous in nature, it becomes very difficult to maintain the execution of tasks once a process is completed. What once started with callbacks soon turned to promises, async module, generators and yield, and async and await. Let's start with async/await 101:

  • Async/await is one of the modern ways to write asynchronous code
  • Built on top of promises, it cannot be used with plain callbacks or Node promises
  • Async/await is non-blocking code even though it appears synchronous, which is its main power
  • Based on node-fibers, it is lightweight and is TypeScript friendly as typings are embedded

Let's now see a practical implementation of async/await. What once started as huge callback hell and nested chains of .then() can simply be reduced to the following:

let asyncReq1=await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log(asyncReq1.data);
let asyncReq2=await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log(asyncReq2.data);

We will now look into two common async/await design patterns.