Reputation:
I'm breaking up a Node Endpoint so that 2 things happen
controller.js
exports.signup = (req, res) => {
methods.checkUser('email', req.body.email)
.then(methods.addUser(req.body.email, req.body.password))
.then(() => {
res.send('added');
})
.catch((err) => {
console.log(err);
res.status(403).send(err);
});
};
methods.js
exports.checkUser = (key, val) => {
return new Promise((resolve, reject) => {
db.query('SELECT * FROM ?? WHERE ?? = ?', ['users', key, val], (err, result) => {
if (result) {
resolve(result);
} else {
reject(err);
}
});
});
};
exports.addUser = (email, password) => {
return new Promise((resolve, reject) => {
if (email === '[email protected]') {
resolve(true);
} else {
console.log('rejecting');
reject(email);
}
});
};
addUser()
currently just checks if the email ===
[email protected]
to test out the Promise chain.
So the endpoint returns added
in Postman
But Terminal shows the following
rejecting
(node:71904) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): [email protected]
(node:71904) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Typically I would have wrote it like this.
exports.signup = (req, res) => {
methods.checkUser('email', req.body.email)
.then(() => {
methods.addUser(req.body.email, req.body.password)
.then(() => {
res.send('added');
})
.catch((err) => {
res.status(403).send(err);
})
})
.catch((err) => {
console.log(err);
res.status(403).send(err);
});
};
I want to take a cleaner approach but need help
Upvotes: 0
Views: 72
Reputation: 16311
This is a correct way to write the Promise chain:
exports.signup = (req, res) => {
methods.checkUser('email', req.body.email)
.then(() => methods.addUser(req.body.email, req.body.password) )
.then(() => res.send('added') )
.catch((err) => {
console.log(err);
res.status(403).send(err);
});
};
so in case of a reject
in the chain, like in the case of the [email protected]
input in the example, the rejection will be handled by the last catch
.
Upvotes: 1