transporter.sendMail does not return a promise, it uses a callback function. change your code
return new Promise((resolve,reject)=>{
let transporter = nodemailer.createTransport({
//settings
});
var mailOptions = {
//mailoptions
};
let resp=false;
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log("error is "+error);
resolve(false); // or use rejcet(false) but then you will have to handle errors
}
else {
console.log('Email sent: ' + info.response);
resolve(true);
}
});
})
}
as I said earlier, transport.sendMail() function uses call back that's why you can not use await there.But you can write a wrapper function around it so that you can use await in your functions where you need more readble and clean code. just consider the following example
async function wrapedSendMail(mailOptions){
return new Promise((resolve,reject)=>{
let transporter = nodemailer.createTransport({//settings});
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log("error is "+error);
resolve(false); // or use rejcet(false) but then you will have to handle errors
}
else {
console.log('Email sent: ' + info.response);
resolve(true);
}
});
}
})
Now you can use this wrappedSendMail function in your other functions like below,
sendmail= async(req)=>{
var mailOptions = {
//mailoptions
};
let resp= await wrapedSendMail(mailOptions);
// log or process resp;
return resp;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…