我正在尝试向某人发送电子邮件。我在控制台中打印成功消息,并且我的代码可以正常工作并成功发送电子邮件,但是当我在代理中将其作为消息打印时,它在响应之前显示为不可用。这是我的代码:
function sendEmail(agent){
//get email and name and message and subject
console.log("Email befor getting: " +fetchedEmail);
getEmail(agent.parameters.name).then(function(){
console.log("the email is fetched: "+fetchedEmail);
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '*********@gmail.com',
pass: '*******************'
}
});
var mailOptions = {
from: '*******@gmail.com',
to: fetchedEmail, //receiver email
subject: agent.parameters.subject,
text: agent.parameters.message
};
return createMessage(mailOptions,transporter).then(()=>{
console.log("email sent successfully");//this message printed on console
agent.add(`email sent successfully`);// this not printed in agent
}).catch(()=>{
agent.add(`fail`);
});
});
}// end of send email
function createMessage(mailOptions,transporter){
return new Promise((resolve,reject)=>{
// i promise to send email
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log("there is error");
reject(error);
} else {
console.log("success");// printed on console
resolve('Email sent: ' + info.response);
}
});
});
}//end of create message
//---
答案 0 :(得分:0)
问题是您正在使用Promises执行异步功能(对getEmail()
和createMessage()
的调用),但是您没有从sendEmail()
本身返回Promise。
如果您正在执行异步功能,则Dialogflow库要求返回一个Promise,以便Intent Handler调度程序知道您正在执行异步功能。
对于您来说,最简单的方法是从getEmail().then()
链中返回Promise。因此,更改这样的行应该有效:
return getEmail(agent.parameters.name).then(function(){