DEV Community

Cover image for Async Await in Javascript
Deepansh Bhargava
Deepansh Bhargava

Posted on

Async Await in Javascript

So in the last post, we learned about how promises work in javascript.

Today, we gonna learn about how async-await works together for the seamless working of promises and makes the developer experience better.

The concept of async-await comes into use when we have more than 2 promises, the code becomes messy and sometimes unbearable.

If you remember the previous example of making a promise, that's great. If not here it is:

const isNumEven = (num) => new Promise((resolve, reject)=> {
  if(num % 2 === 0) {
    resolve(true)
  } else {
    reject(false)
  }
})
Enter fullscreen mode Exit fullscreen mode

Now this promise can be used as:

async function isEven(num) {
  try {
    const result = await isNumEven(num);
    return result;
  } catch(err) {
    console.log('Something went wrong!')
  }
}

isEven(4); // true
Enter fullscreen mode Exit fullscreen mode

As you can see, it makes our code less sloppy and easier to manage. Now if the isNumEven function returns another promise, then we can use await again and get the result.

Now some of you must be wondering why try catch is used in this example?

The answer to this is error handling. If any of the statements fail in the try block, then the code directly goes into the catch block. So, if our promise fails, the error will be handled by the catch block.

Some important points related to async await:

  • Avoid using it inside for loops, and if there is a need to perform an operation on all entities use Promise.all rather than async await.

  • If you have used the async keyword before a function, it'll return a promise every time.

  • Async await is just syntactic sugar for promises, the code runs the same way as it runs for promises. The code looks synchronous and the program waits until the promise is resolved.

  • If a function is async, then only you can use await inside it.

Connect with me on Twitter, Instagram & LinkedIn

Happy Coding!

Top comments (0)