Breaking and taming the Promise chain in JS
Before a .then() chain brings you back to the callback hell
You have probably read a lot about Promises
and how they can help tidying up your code, replacing the old callback
s. Yet, when your code has to execute a number of operations, you might as well end up in a .then()
chain that looks pretty much like the “callback hell” you were trying to escape from.
You also probably know about Promise.all()
. It helps tidying up Promise
chains, but what if you need to pass return variables across the chainedPromise
s? You might need to resort to workarounds that make your code more complex and less readable.
There are better ways to implement Promise chains. Let’s take a piece of ugly, old-school code and improve on that.
Driving a car, the wrong way
Take a look at this code (…I dare you!):
'use strict'function doAction(action) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`${action}: done.`)
}, 1000)
})
}console.log('Getting ready to drive the car...')// Welcome to the "callback hell", the place where
// all bad programmers go ;)
// This is an example of how NOT to write JS…