代码正确运行并在控制台上打印成功消息,但无法在应用程序中打印

时间:2019-04-17 12:21:05

标签: node.js dialogflow

我正尝试向多个人发送电子邮件,我从火力基地获取地址并将其存储在称为部门电子邮件的数组中,然后我遍历该数组并将电子邮件发送至每个地址,代码正常工作并全部发送电子邮件。我的问题是,在发送所有电子邮件之后,代码在哪里写agent.add(“所有电子邮件发送成功”)

function sendEmails(agent){
//ask for department number and subject and message
  var sub=agent.parameters.subject;
  var msg=agent.parameters.message;


  return getEmailsForDepartment(agent.parameters.departmentNO).then(function(){

    departmentEmails.forEach(function(email){
      return createMessagesForDepartment(sub,msg,email).then(()=>{
        console.log("email sent successfully");

      }).catch(()=>{
       console.log(`fail`);
      });

    })

  });
}// end of send emails

//this function to get all addresses from database 
function getEmailsForDepartment(numOFDepartment){

  var query = admin.database().ref("/"+departmentsNo[numOFDepartment]).orderByKey();
  return query.once("value").then(function(snapshot){
    snapshot.forEach(function(childSnapshot){
      departmentEmails.push(childSnapshot.child('email').val());
    });

  });

}


function createMessagesForDepartment(sub,msg,emailAdd){
  return new Promise((resolve,reject)=>{
    // i promise to send email
    const nodemailer = require('nodemailer');
    const transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: '****@gmail.com',
        pass: '****'
      }
    });
    var mailOptions = {
      from: '*****@gmail.com',
      //how to send for all emails in array
      to: emailAdd, //receiver email
      subject: sub,
      text: msg
    };


    transporter.sendMail(mailOptions, function (error, info) {
      if (error) {
        console.log(error);
        reject(error);
      } else {
        console.log('Email sent: ' + info.response);

        resolve('Email sent: ' + info.response);
      }
    });



  });


}//end of create message

2 个答案:

答案 0 :(得分:0)

agent.add()函数不能像console.log()那样工作。它不会立即将消息发送给用户,通常您只能向用户发送一条消息。所以我不希望它能打印出三遍。

如果您需要查看每个消息,请在循环期间构建一个字符串,然后使用该构建的字符串调用agent.add()

答案 1 :(得分:0)

我会保留剩余的待发送电子邮件数量。用部门电子邮件的数量初始化此号码。然后,成功发送的每封电子邮件的回叫将减少该数字。当回调函数发现剩余要发送的电子邮件数量为零时,您可以安全地报告所有电子邮件已发送。

return getEmailsForDepartment(agent.parameters.departmentNO).then(function(){

  // Initialize a counter here.
  let numberOfEmailsRemainingToSend = departmentEmails.length;

  departmentEmails.forEach(function(email){

    return createMessagesForDepartment(sub,msg,email).then(()=>{
      console.log("email sent successfully");

      // Decrement the counter here.
      if(!--numberOfEmailsRemainingToSend)) {
        // When the counter reaches zero, all tasks are complete.
        agent.add("all email sent successfully")
      } 

    }).catch(()=>{
      console.log(`fail`);
    });

  })

});