We've got this node.js code which is called by an Express route:
routes.login = (req, res) => {
let inpEmail = req.body.email.toLowerCase(),
inpPassword = req.body.password,
loginFailureCount = 0;
// find the user
User.findOne({
email: inpEmail
}).exec()
.then((user) => {
//get existing login failure count
loginFailureCount = user.loginFailureCount;
if (user.isLocked && Date.now < user.lockExpiry) {
//some logic here
} else if (!user.emailVerified) {
//some logic here
} else {
bcrypt.compare(inpPassword, user.passwordHash).then((compareResult) => {
// check if password matches
if (compareResult) {
//some logic here
setLoginFailureCount(user, loginFailureCount).then(() => {
setLastLogin(user)
.then(() => {
//some logic here
})
.catch((err) => {
//some logic here
});
})
.catch((err) => {
//some logic here
});
} else {
//login failed
loginFailureCount = loginFailureCount + 1;
setLoginFailureCount(user, loginFailureCount)
.then(() => {
//some logic here
})
.catch((err) => {
//some logic here
});
}
});
}
})
.catch((err) => {
//some logic here
});
}
All looks good, and we feel that the promises are not used correctly; there are multiple catch
statements.
One of my colleague said that:
Ideally, the code structure with promises shall look like this:
someFunction() .then() .then() .then() .catch();
Since, there are multiple if-else
statements. We were trying to brainstorm if the above kind of chaining can be implemented or not.
Is there a better way to implement promises in this code?