Flattening Nested Promises in Javascript

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)
});

Senior Software Engineer. Making computers do stuff since 2011.

Senior Software Engineer. Making computers do stuff since 2011.