SN Blog

Why to use async & await instead of the Promise class?

☕ 3 min read 329

Why to use async & await instead of the Promise class?

In order to answer this question we should first say what are actually promises and what they do.

What are promises

Promises are a way to write asynchronous code, which means that a function will return some data in a certain time in the future and the code will continue to execute. For example let's say we want to make a burger because we are hungry. So what we do, we can put the meat on the stove, and in parallel with this we can cut the vegetables. When the meat is ready we remove it from the hot plate and put it in the burger, then we put the vegetables and we are ready. Cooking the meat is the Promise and when it is ready we do something with it, this is what we call asynchronous programming.


Here a simple function that get some data load some data. These are the two ways to do it with the Promise class which has 2 methods .then when the promise has ended and .catch when there is an error.

What we see is that using async & await we write less code but in this way when there is 1 function it doesn't matter if you use await or promise class. But what will happen if there are 2 or more functions that depend on each other. For example, first we want to get a user and then we want to get all clubs that a user has joined. Here are the 2 implementations.

When looking at the first example it gives you a headache. It’s easy to get lost in that nesting, braces. You can see in the second example that the code with async & await is more clean and easy to read. And also what we deal with is the callback hell. Async & await is a syntactical sugar for writing asynchronous code. It makes the code look and behave a little more like synchronous code but it remains to be asynchronous.


Some people may say that using async & await can make the asynchronous code less obvious. But C# had this feature for years and people who are familiar with it know it’s worth this minor, temporary inconvenience.


Add a comment