我正在尝试使用async/await
使用for循环发送电子邮件。
const prepareNotification =(genie)=>{
genie.forEach(async (item)=>{
if(item.is_active){
if(item.is_email){
sendEmailNotification(item);
}
}else{
console.log('deal genie inactive for',item.name);
}
});
}
要发送,我需要从文件中读取HTML并发送到邮件功能。
const sendEmailNotification=async (item)=>{
try{
let emailTemplate = await fs.readFile(__basedir+'/controllers/html/sharedeal.html','utf-8');
console.log(emailTemplate);
let replacements = {
dealLink:'testlinkhere'
};
let mailOptions = {
from: process.env.smtpEmail,
to: item.email,
subject: 'DealLink',
replacements:replacements,
template:emailTemplate
};
let mail = await sendEmail(mailOptions);
}catch(error){
console.log(error);
}
}
但是我在undefined
上得到了console.log(emailTemplate);
,还有一个问题,我如何确保sendEmailNotification
在for循环中的每个状态下都依次执行? >
答案 0 :(得分:1)
fs.readFile
不支持async/await
。但是您可以创建一个执行以下操作的版本:
const util = require('util');
const readFileAsync = util.promisify(fs.readFile);
然后
let emailTemplate = await readFileAsync(__basedir+'/controllers/html/sharedeal.html','utf-8');
console.log(emailTemplate);
我如何确定sendEmailNotification在for循环中的每个状态下都依次执行?
const prepareNotification = async (genie) => {
for (let item of genie) {
if(item.is_active){
if(item.is_email){
await sendEmailNotification(item);
}
}else{
console.log('deal genie inactive for', item.name);
}
}
}
或
const prepareNotification = (genie) => {
genie.reduce((prev, item) => {
if(item.is_active){
if(item.is_email){
return prev.then(() => sendEmailNotification(item));
}
}else{
console.log('deal genie inactive for', item.name);
}
return prev;
}, Promise.resolve());
}