首页 > 解决方案 > 如何使其仅在使用 async await 生成 pdf 后才发送 pdf

问题描述

如何使邮件传输器等到生成pdf?

我附上了我尝试过的代码。我的浏览器挂起,无法发送电子邮件。问题是邮件传输器尝试在生成 pdf 之前发送电子邮件。我猜我没有在正确的地方使用异步和等待。

      async () => {
        await pdf.create(document, options).then(res => {
          console.log(res)
        }).catch(error => {
          console.error(error)
        })

        let message = "Testing"

        let mailOptions = {
          from: "xxx@gmail.com",
          to: "yyy@gmail.com",
          subject: 'Subject testing',
          text: message,
          attachments: [{
            path: __dirname + '/../public/reports/' + 'test.pdf',
          }]
        }

        await transporter.sendMail(mailOptions, (error, info) => {
          if (error) {
            console.log(error);
          } else {
            console.log("sent email")
            res.json({
              email: "sent"
            });
          }
        })
      }

标签: node.jsexpressasynchronouspdf-generationsendmail

解决方案


我想到了。我没有调用该函数,因此未执行该操作。我删除了 transporter.sendMail 中的等待,因为它没有做任何事情。

  sendPDF();
  async function sendPDF() {
    await pdf.create(document, options).then(res => {
      console.log(res)
    }).catch(error => {
      console.error(error)
    })

    let message = "Testing"

    let mailOptions = {
      from: "xxx@gmail.com",
      to: "yyy@gmail.com",
      subject: 'Subject testing',
      text: message,
      attachments: [{
        path: __dirname + '/../public/reports/' + 'test.pdf',
      }]
    }

    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        console.log(error);
      } else {
        console.log("sent email")
        res.json({
          email: "sent"
        });
      }
    })
  }

推荐阅读