A few reasons Async / Await beat Promises

Tram Ho

Well, this article is from 2017, but I feel good to share with you guys, especially what you are starting to learn … like me. ✌️

In case you have forgotten, Node.js has supported async / await since version 7.6. If you haven’t tried it, this article will list the reasons with examples to explain why you should choose it.

Async / await 101

For those who haven’t heard of Async / await, here are some brief introductions:

  • Async / await, like promises, is non-blocking.
  • Async / await makes asynchronous code look and run almost like synchronous code.
  • Async / await is a new way to write asynchronous code. Previous methods of working with asynchronous code were the use of callbacks and promises.
  • Async / await is a concept built on top of the promise. Therefore it cannot be used with pure callbacks.

Syntax

Assuming a getJSON function returns a promise, that promise contains several JSON objects. We need to call that function, log out the JSON objects, then return "done" .

The following code describes the process above, using promises.

And the code uses Async / Await

There are a few differences to look out for:

  • The function has more async keywords ahead. The await keyword is only used inside a function defined with async. Any async function will return a promise implicitly, and the resolved value of the promise will be whatever the return function (in this case, the string “done”).
  • The above comment also means that we can not use await in front of the code containing the async keyword.

  • await getJSON () means that the console.log call will wait until the promise getJSON () is processed and returned the value.

What are the advantages of Async / await?

  1. The code is shorter and cleaner
  • The simplest is that the amount of code we need to write has decreased significantly. In the above example, it is clear that we have saved a lot of lines of code. We don’t need to write .then, create an anonimous function to handle the response, or name the data for a variable we don’t use. We avoid nested code blocks. These small benefits will accumulate gradually in large code, real projects and will become very valuable.
  1. Error handling
  • Async / await helps us to handle both synchronous and asynchronous errors in the same structure. Bye try / catch. For the code below using promises, try / catch will not catch errors if JSON.parse fails because it occurs inside promises. We need to call .catch inside the promise and repeat the error handling code, which is definitely more troublesome than console.log in the production code.

Now look at the code using async / await. The catch block will now handle parsing errors.

  1. Conditional statements
  • Take a look at the following code snippet. This code will fetch data and decide whether to return the value or get more data.

The code gradually resembles the “xyz hell” model we often see. Total code has 6 nested levels. When using async / await, we will have a new code easier to read.

  1. Intermediate value
  • You’ve probably been in the following situation: you need to call promise1, then use the value it returns to call promise2, finally use the results of both promises above to call promise3. Your code will turn out like this.

If promise3 doesn’t require value1, the promise will reduce the nest class by a bit. If you are perfectionist, you can solve it by wrapping both value1 and value2 with Promise.all, avoiding nest classes like the code below.

This method sacrifices semantics in exchange for legibility of the code. Simply because there is no reason that value1 and value2 are put together in one array, except doing so will avoid nesting promises.

However, this logic becomes extremely silly when we use async / await.

  1. Error Stack
  • Imagine a piece of code calling multiple promises in series. At some point, the code will throw an error

The Error Stack returned from the promise chain cannot help us determine where the error occurred. Worse, it also makes us misunderstand that the error lies in the callAPromise function.

However, with async / await, Error Stack will indicate which function contains the error.

  • When you develop an application in a local environment, this may not seem like much effect at first glance. However, with a production server, it is very useful with Error Logs. In those situations, it’s much better to know that the error occurred in makeRequest when it was reported that the error is in the then then then the back then ….
  1. Debugging
  • The last great thing when you work with async / await is that the debugging becomes very simple. Debug with Promise has never been a pleasant job for two reasons:
  1. You cannot set a breakpoint in an arrow function that returns an expression.
  2. If you put a breakpoint inside the .then block and use short-cut debug like step-over, the debugger will not move to the next .then block because it only “step” in the synchronized code. With async / await, you don’t need the arrow function too much, you can step through the await call just like with synchronous code.

Conclude

  • Async / await is one of the revolutionary features added to JavaScript in recent years. It helps you realize how short the Promise is, as well as providing an alternative.
  • Reference: hackernoon
Share the news now

Source : Viblo