Breaking and taming the Promise chain in JS

Before a .then() chain brings you back to the callback hell

Edoardo Nosotti
RockedScience
Published in
4 min readMay 20, 2019

--

Photo by Victor Rodriguez on Unsplash

You have probably read a lot about Promises and how they can help tidying up your code, replacing the old callbacks. 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 chainedPromises? 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…

--

--

Edoardo Nosotti
RockedScience

Certified Cybersecurity Analyst and Senior Cloud Solutions Architect. Passionate about IoT, AI, ML and automation.