Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 9, 2020 08:13 pm GMT

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.

Usage

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. Its 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.

Conclusion

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 its worth this minor, temporary inconvenience.


Original Link: https://dev.to/svetloslav15/why-to-use-async-await-instead-of-the-promise-class-4can

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To