I am new in asynchronous programming in javascript. I have two email provider sendgrid and mailgun. i want to send email with one of this then if any error happened, resend email with another one. finally if email sent successfully save into db and response with json object. here is my code :
if(req.query.provider== 'mailgun'){
console.log('sending with mailgun ...');
mailgun.messages().send(data, function (err, res) {
if(err){
fail = true;
console.log(`error in sending email with mailgun. error :${err}`)
} else {
console.log('email sent with mailgun')
fail = false;
}
});
}else if(req.query.provider == 'sendgrid'){
console.log('sending emial with sendgrid')
sendgrid.sendMail(data, function(err, res) {
if (err) {
console.log(`error in sending with sendgrid. error: ${err} + response : ${res}`)
fail = true
}
console.log(`email sent with sendgrid`)
fail = false
});
}
if(fail){
if(req.query.provider == 'mailgun'){
console.log('sending with sendgrid ...')
sendgrid.sendMail(data, function(err, res){
if(err){
console.log(`error: ${err} + response : ${res}`)
}else {
console.log(`response: ${res}`)
fail = false
}
})
}else if(req.query.provider == 'sendgrid'){
console.log('sendging with mailgun')
mailgun.messages().send(data, function (err, res) {
if(err){
console.log(`error: ${err} + response : ${res}`)
}else{
console.log(`response: ${res}`)
fail = false
}
})
}
}
if(!fail){
db.models.Email.create(req.query, (err, result)=>{
if(err){
handleErrors(res, err);
console.log(`error in creating Email :${err}`)
}else {
console.log()
res.json(result)
}
});
} else {
console.log('fail in sending error');
res.json('sorry.');
}
});
the problem here is, this code run asynchronously. for example, it sent with mailgun then jump to fail check and send again with sendgrid. doesn't wait for the response of sending.
how can I fix and improve this ? should I use async',
await'?