I'm trying to register as user in my mongodb, if that goes well I want to send an email to the registered user. To do that i'm using sendgrid, which ships with a .send(msg) which returns a promise .catch(error) and .then({...}).
If the error is present I want to send a response to the webpage, that the user was registered, but the email failed. I cannot do that directly from the .catch() since it is in another part of the application, out of scope and should be used by multiple other functions....
sendgrid.js
module.exports.sendRegMail = function (user, password, adminUserID, adminName, success, errorCB) {
msg.to = email;
msg.subject = `Welcome ${user.name}! You have been registered!`;
msg.text = `Dear ${user.name}.\nYou just been registered as a ${user.userType}.\n\nPlease log in with following credentials:\nUsername: ${user.username}\nPassword: ${password}\n\nOBS: it is important that you change your password to a personal one in order to use the platform!\nMost features will be disabled until your account has been secured with a personal password.`;
sendMail(msg, success, errorCB);
}
function sendMail(msg, success, errorCB){
sgMail.send(msg)
.then(() => {
Logger.logUserAction(userID, name, 'Successfully sent email:\n' + JSON.stringify(msg));
success();
})
.catch(error => {
Logger.logUserAction(userID, name, 'Tried to send email:\n' + JSON.stringify(msg) + '\nBut failed due to error:\n' + error);
errorCB();
});
}
cut out from where the user is being saved....
User.addUser(newUser, (err, user) => {
if (err) {
Logger.logAdminAction(decoded.data._id, decoded.data.name, 'Tried to register user: ' + user + '. but failed. Error: ' + err);
res.json({ success: false, msg: 'Failed to register user' });
} else {
Logger.logAdminAction(decoded.data._id, decoded.data.name, 'Successfully created user: ' + user);
mail.sendRegMail(user, req.body.password, decoded.data._id, decoded.data.name, ()=>{
res.json({ success: true, msg: 'User registered, And email sent successfully!' })
}, () =>{
res.json({ success: true, msg: 'User registered, but email could not be sent! Contact the person manually.' })
});
}
});
as for now i'm trying to give two callback functions as argument in sendRegMail(). and then call one callback in .then() and another callback in .catch() But it seems to me over complicated this way? What is the correct way of handling a promise error/success from a parent function??