DEV Community

Discussion on: What's your favorite addition to ES2015+

Collapse
 
lexlohr profile image
Alex Lohr

Async/await is so great. No more callback hell ever again.

Collapse
 
jckuhl profile image
Jonathan Kuhl

First time I used Async/Await was a Vue project with a Java Servlet backend. Plopped await in front of the fetch that connected with my back end, and async in front of vue's mounted() method and squealed in delight when my component rendered with my data base information for the first time.

Multiple moments of triumph at once, first use Async/Await, first success with a servlet, and was still new to Vue.JS.

Collapse
 
laurieontech profile image
Laurie

Ah callback hell. Such fun.

Collapse
 
anastely profile image
Anas T

Example?

Collapse
 
lexlohr profile image
Alex Lohr

Let's say, you need to sequentially resolve three promises. Callback hell looks like this:

function asyncJob(callback) {
  asyncA(xyz, (err, buffer) => {
    if (err) { throw err; }
    asyncB(buffer, (err, result) => {
      if (err) { throw err; }
      asyncC(result, (err, response) => {
        if (err) { throw err; }
        if (response.ok()) { return callback(); }
        throw new Error('Could not send result');
      });
    })
  });
}

Now the same with Promises:

const asyncJob = () => asyncA(xyz)
.then((buffer) => asyncB(buffer))
.then((result) => asyncC(result))
.then((response) => {
  if (response.ok()) { return Promise.resolve(); }
  throw new Error('Could not send result');
});

Reads a lot better, doesn't it? Still, it's pretty terse and has a lot of repetition, so async/await is a big improvement when it comes to reading flow:

const asyncJob = async () => {
  const buffer = await asyncA(xyz);
  const result = await asyncB(buffer);
  const response = await asyncC(result);
  if (!response.ok()) {
    throw new Error('Could not send result');
  }
};
Thread Thread
 
laurieontech profile image
Laurie

We call the second thenable hell.
I'm a fan of Promise.all as a solution, but I acknowledge async/await is a great option too.

Thread Thread
 
lexlohr profile image
Alex Lohr

.then(...) still takes a callback. So while it reads much more congruently, it's basically still good old callback hell, just in a better suit and with better manners. Async/await is a game changer when it comes to readability of asynchronous code.