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');
}
};
Software dev at Netflix | DC techie | Conference speaker | egghead Instructor | TC39 Educators Committee | Girls Who Code Facilitator | Board game geek | @laurieontech on twitter
.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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Let's say, you need to sequentially resolve three promises. Callback hell looks like this:
Now the same with Promises:
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:
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.
.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.