gpt4 book ai didi

javascript - 如何适时地使用异步和同步编程

转载 作者:行者123 更新时间:2023-12-03 03:35:50 25 4
gpt4 key购买 nike

我是 javascript 异步编程的新手。我有两个电子邮件提供商 sendgrid 和 mailgun。我想使用其中之一发送电子邮件,然后如果发生任何错误,请使用另一封电子邮件重新发送。最后,如果电子邮件发送成功,则保存到数据库中并使用 json 对象进行响应。这是我的代码:

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

这里的问题是,这段代码是异步运行的。例如,它使用mailgun发送,然后跳转到失败检查并使用sendgrid再次发送。不等待发送的响应。我该如何解决和改进这个问题?我应该使用async',await'吗?

最佳答案

这里是一个使用 async/await 的示例图案

(可以改进以支持一般的多个邮件程序,您必须调整选择替代邮件程序名称的部分)

  /**
* Send an email using a given mailer
*
* return true if success, false otherwise
*/
async sendMailUsingMessages(mailerName, data) {
const {
mailer,
func,
} = [
{
mailer: 'mailgun',
func: async () => mailgun.messages().send(data);
},
{
mailer: 'sendgrid',
func: async () => sendgrid.sendMail(data);
},
].find(x => x.mailer === mailerName);

console.log(`sending with ${mailer} ...`);

try {
const res = await func();

console.log(`email sent with ${mailer}`);

return true;
} catch (err) {
console.log(`error in sending email with ${mailer}. error :${err}`)

return false;
}
}

/**
* Send an email
*/
async sendEmail(req, res, data) {
if (!(await sendMailUsingMessages(req.query.provider, data))) {
// One fail, so we try the other one
const alternativeMailerName = req.query.provider === 'mailgun' ? 'sendgrid' : 'mailgun';

if (!(await sendMailUsingMessages(alternativeMailerName, data))) {
// Double fail
console.log('fail in sending error');

res.json('sorry.');

return;
}
}

// Success
try {
const result = await db.models.Email.create(req.query);

res.json(result);
} catch (err) {
handleErrors(res, err);

console.log(`error in creating Email :${err}`)
}
}

关于javascript - 如何适时地使用异步和同步编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45863525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com