我正在尝试从由另一个Micro服务(Rest API)加载的Amazon SQS(队列服务)中获取数据。我正在使用此数据中的参数和属性来发送电子邮件。无需等待nodemailer sendMail完成执行。我在SO Q&A中读到nodemailer支持回调,并且现在也在等待(如果Node版本高于8)。但是他们两个都不起作用。在完成nodemailer的sendMail执行之前,将返回API调用。电子邮件已发送,API完成了执行。但是在sendMail完成之前将返回呼叫。
我总是收到502错误的网关响应。
下面是sendMail的代码。
sendMail(body: MailObject): Promise < boolean > {
const senderAddress: Mail.Address = {
address: body.from.emailAddress,
name: body.from.name ? body.from.name : ''
}
const recipientAddress: Mail.Address = {
address: body.to.emailAddress,
name: body.to.name ? body.to.name : ''
}
const mailOptions: Mail.Options = {
from: senderAddress,
to: recipientAddress,
subject: body.subject,
text: body.text ? body.text : undefined,
html: body.html ? body.html : undefined,
amp: body.html ? body.html : undefined
}
return new Promise<any> (async (resolve, reject) => {
if (!this.transporter) {
this.logger.warn(`Transporter not intitialized. Use connect method`);
reject(`Transporter not initialized. Use connect method`);
}
console.log(`[location]: [sendMail][promise]`);
console.log(`[Mail Options]: ${JSON.stringify(mailOptions)}`)
this.transporter.sendMail(mailOptions, (error, data)=>{ //<--- I have also tried await
if(error){
console.error(`[sendMail][error]: ${error}`);
reject(error);
}
else{
console.log(`[sendMail][data]: ${data}`);
resolve(true);
}
})
})
}
请参考下面的最终日志片段。返回值的http状态为200。但是在API调用返回ARC / postman上的502错误网关后,将记录该状态。
在API调用在邮递员上显示502错误的网关后,会记录以上响应。
正如Dani在问题的注释部分中提到的那样,上面的代码中没有此问题。问题是它没有等待服务完成从SQS提取数据的过程。
向AWS SQS的receiveMessage函数添加了promise(请参阅注释以获取第一行代码)。
this.sqs.receiveMessage(params).promise().then(async data=>{ //<--- Added promise here
console.log(`[MessageBody]: ${data.Messages![0].Body}`);
this.message = {
MessageId : data.Messages![0].MessageId||"",
ReceiptHandle : data.Messages![0].ReceiptHandle||"",
MD5OfBody : data.Messages![0].MD5OfBody||"",
Body : data.Messages![0].Body||"",
MD5OfMessageAttributes : data.Messages![0].MD5OfMessageAttributes||"",
MessageAttributes : {
from: {
StringValue: data.Messages![0].MessageAttributes!.from.StringValue||"",
StringListValues: data.Messages![0].MessageAttributes!.from.StringListValues||{},
BinaryListValues: data.Messages![0].MessageAttributes!.from.BinaryListValues||{},
DataType: data.Messages![0].MessageAttributes!.from.DataType||""
},
subject: {
StringValue: data.Messages![0].MessageAttributes!.subject.StringValue||"",
StringListValues: data.Messages![0].MessageAttributes!.subject.StringListValues||{},
BinaryListValues: data.Messages![0].MessageAttributes!.subject.BinaryListValues||{},
DataType: data.Messages![0].MessageAttributes!.subject.DataType||""
},
to: {
StringValue: data.Messages![0].MessageAttributes!.to.StringValue||"",
StringListValues: data.Messages![0].MessageAttributes!.to.StringListValues||{},
BinaryListValues: data.Messages![0].MessageAttributes!.to.BinaryListValues||{},
DataType: data.Messages![0].MessageAttributes!.to.DataType||""
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句