DEV Community

Cover image for  Why you should be using async/await
Gordon_Gao
Gordon_Gao

Posted on

Why you should be using async/await

​Promises are an incredibly important part of JavaScript. It allows us to hook into the completion of asynchronous calls, making chained asynchronous operations simple.

But there is a (not so) tiny downside - Promises are not the best solution in terms of prettiest syntax.

The async and await keywords are syntactic sugar for Promises. They aid in presenting the asynchronous code in a synchronous way. They introduce no new concepts, but they change the way that Promise-based code is written.

Before/after async/await


Here is some code that uses plain Promises:

const doAsynchronousStuff = ...; // function that returns a Promise

doAsynchronousStuff().then(result1 => {
  return doAsynchronousStuff(result1);
}).then(result2 => {
  return doAsynchronousStuff(result2);
}).then(result3 => {
  return doAsynchronousStuff(result3);
}).catch(e => {
  // handle the error
});


Notice the use of callback functions. However, with async/await this becomes:

try {
  const result1 = await doAsynchronousStuff();
  const result2 = await doAsynchronousStuff(result1);
  const result3 = await doAsynchronousStuff(result2);
} catch (e) {
  // handle the error
}


Notice how it looks just like regular, synchronous, non-Promise-based code, except it supports waiting for the Promise to be resolved!
Collapse

Top comments (3)

Collapse
 
savagepixie profile image
SavagePixie

If you want to compare them in terms of prettiness, the very least you could do is choose a good example of promises, not something that looks ugly for no reason.

doAsynchronousStuff() 
    .then(doAsynchronousStuff)
    .then(doAsynchronousStuff)
    .then(doAsynchronousStuff)
    .catch(e => {
       // handle the error
    });
Collapse
 
bettercodingacademy profile image
Better Coding Academy

To be fair, the async/await example could easily be extended to include additional transformation on the values resolved from each Promise; however, that no longer is possible with this type of shortening. For example:

const result1 = await doAsynchronousStuff();
const data1 = transform(result1);
const result2 = await doAsynchronousStuff(data1);
const data2 = transform(result2);
const result3 = await doAsynchronousStuff(data2);

^ This is only possible in a callback-based Promise syntax when expanded callbacks are used.

Collapse
 
savagepixie profile image
SavagePixie • Edited

Sure you can!

doAsynchronousStuff()
   .then(transform)
   .then(doAsynchronousStuff)
   .then(transform)
   .then(doAsynchronousStuff)

To be entirely fair, both syntaxes can be expanded to become more complex than this simple example and both can be used to write ridiculously awkward code. My sole point is that in order to compare different things, you should strive to use the best of both groups, rather than making up examples that suit your point.