Javascript异步/等待:读取文件时发生未定义的错误

时间:2018-10-23 07:36:54

标签: javascript node.js async-await 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);
   }
}

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

1 个答案:

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