Skip to main content

Command Palette

Search for a command to run...

Async, Await use over Promise with examples.

Updated
2 min read

The objective of this blog is to summarize the understanding of Async function and some brownie points of using it compared to Promises.

What is Async and Await ?

Async and Await are keywords(in JS) which are used to give asynchronous(i.e promise-based behavior ) powers to a function if a function is declared in format below:-

async function getLikes() {
  const result = await getPostLikes();
  console.log(result);
  // expected output: "resolved"
}

Let's understand the above code snippet,

  1. getLikes is a async function name ,as it getLikes is declared with *async * keyword .

2.Function body containing await mechanism.

3.Function (getLikes here) always return a promise(if not explicitly then implicitly).

Understanding how Await is used here

  • Async functions can contain zero or more await expressions.

  • Await when used in async function suspend execution until the returned promise is fulfilled or rejected, and this way mimic the synchronous behavior.

  • The use of await keyword is only valid inside async functions within regular JavaScript code.

Advantages of using it over directly using Promises are:-

  • To simple and more intuitive syntax necessary to consume promise-based APIs.

  • It enables us to use try / catch blocks around asynchronous code.

  • Avoid .then hell

.then hell ?

Let's understand how we will write same function first with using Promise then with Async and Await.

image.png

image.png

With Async Await code it is fairly easy to to read and understand what's the function is trying to acheive.