Flattening Nested Promises in Javascript

Justin Tulk
May 15, 2017 · 1 min read

This post will underwhelm most of you, but people do this (I’ve seen it, and I caught myself doing it today while waiting for my part of a conference call).

The problem: frequently in client-side code two or more async calls will need to be run serially in order to perform the desired task. For example:

// login a user, and then retrieve a JWT token in Firebase
firebase.auth()
.signInWithEmailAndPassword('j@j.com', '12341234')
.then(user => {
user.getToken().then(token => {
// store the token in the Redux store
this.props.setUserJWTToken(token)
})
})

.catch(err => {
console.error(err)
});
// the error will bubble up so a single catch at the bottom handles
// both async calls

This works, but it’s hard to follow. The trick is to return any downstream asynchronous call (if it’s a promise) without the attached .then() method for clean, chained, easy-to-follow code.

// login a user, and then retrieve a JWT token in Firebase
firebase.auth()
.signInWithEmailAndPassword('j@j.com', '12341234')
.then(user => {
return user.getToken()
})
.then(token => {
this.props.setUserJWTToken(token)
})

.catch(err => {
console.error(err)
});

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store