gpt4 book ai didi

JavaScript 异步/等待 : undefined error on file read

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

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

关于JavaScript 异步/等待 : undefined error on file read,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52943560/

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