Javascript async/await : 文件读取未定义错误

Javascript async/await : undefined error on file read

我正在尝试使用 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);
   }
}

但我在 console.log(emailTemplate); 上得到 undefined,还有一个问题,我如何确保 sendEmailNotification 在 for 循环中的每个状态上一个接一个地执行?

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);

how can i make sure that the sendEmailNotification is execute one after another on each state in the for loop??

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());
}