DEV Community

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

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.