如何确定函数执行顺序

时间:2019-02-14 18:12:41

标签: javascript node.js nodemailer node-pdfkit

我正在使用pdfkit制作pdf文件,并使用nodemailer将其作为附件发送到电子邮件,但它会发送0字节的output.pdf。

我猜问题出在函数执行顺序上-它在创建pdf文件之前开始发送电子邮件。我只是不知道该如何解决...

app.post("/addressofpost", function(req, res){
  var abc = req.body.entpost;
  var subj = "pdf text"
"use strict"
const doc = new PDFDocument;
doc.pipe(fs.createWriteStream('output.pdf'));
doc.font('PalatinoBold.ttf')
   .fontSize(25)
   .text(subj, 100, 100);
doc.end();

async function main(){
  let account = await nodemailer.createTestAccount();
  let transporter = nodemailer.createTransport({
    host: "smtp settings",
    port: 465,
    secure: true,
    auth: {
      user: "mailuser",
      pass: "mailpass"
    }
  });
  let mailOptions = {
    from: '"Sender" <sender@gmail.com',
    to: '"Receiver" <receiver@gmail.com>',
    subject: "Subject",
    text: "email text",
    html: "HTML text"
  };
    let mailOptionsPrint = {
    attachments: [
        {  
              filename: 'output.pdf'
        }],
    from: '"Sergei Dudin" <dudinsergey@mail.ru>',
    to: '"Принтер" <info@moypohod.ru>',
    subject: "Subject",
    text: "email text",
    html: "HTML text"

  };
  let info = await transporter.sendMail(mailOptions)
  let infoPrint = await transporter.sendMail(mailOptionsPrint)
  console.log("Message sent: %s", info.messageId);
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}
main().catch(console.error);
  console.log(abc);
  res.send('done');
 });

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您猜对了!

在解决此问题之前,我建议您使app.post处理程序成为异步处理程序,这样就不必在该处理程序中创建另一个异步函数。

app.post("/addressofpost", async (req, res) => {
  // ...
});

此外,我建议您在可能的情况下不要混合使用回调和异步/等待。您可以为回调样式的异步函数创建包装器函数,将其转换为Promise,然后在现在异步的Post处理程序中对它们进行await

// I just extracted the pdf creation logic into a function
const createPdf = subj =>
  new Promise((resolve, reject) => {
    const doc = new PDFDocument();
    const writeStream = fs.createWriteStream("output.pdf");

    writeStream.on("finish", () => {
      resolve();
    });

    // TODO: handle errors and reject the promise accordingly

    doc.pipe(writeStream);
    doc
      .font("PalatinoBold.ttf")
      .fontSize(25)
      .text(subj, 100, 100);
    doc.end();
  });

将那些您现在可以做的事情排除在外:

app.post("/addressofpost", async function(req, res) {
  const abc = req.body.entpost;
  const subj = "pdf text";

  await createPdf(subj);

  let account = await nodemailer.createTestAccount();
  let transporter = nodemailer.createTransport({
    host: "smtp settings",
    port: 465,
    secure: true,
    auth: {
      user: "mailuser",
      pass: "mailpass"
    }
  });
  let mailOptions = {
    from: '"Sender" <sender@gmail.com',
    to: '"Receiver" <receiver@gmail.com>',
    subject: "Subject",
    text: "email text",
    html: "HTML text"
  };
  let mailOptionsPrint = {
    attachments: [
      {
        filename: "output.pdf"
      }
    ],
    from: '"Sergei Dudin" <dudinsergey@mail.ru>',
    to: '"Принтер" <info@moypohod.ru>',
    subject: "Subject",
    text: "email text",
    html: "HTML text"
  };
  let info = await transporter.sendMail(mailOptions);
  let infoPrint = await transporter.sendMail(mailOptionsPrint);
  console.log("Message sent: %s", info.messageId);
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));

  console.log(abc);
  res.send("done");
});