Node.js nodemailer - 等待新承诺解决错误

Node.js nodemailer - Await new promise resolve error

我将 node.js 与 nodemailer 一起使用,结果如下:

let mail = await new Promise((resolve,reject)=>{
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        console.log(error);
        reject(error);
    } else {
        res.status(200).json({ "success": true, "message": 'Thank you for your registration! We\'ve sent you an email to confirm!' });
        resolve(mail);
    }
  });
});

正在发送邮件,但我收到此错误:

/home/project/controllers/signup.js:139
                        resolve(mail);
                                ^
ReferenceError: mail is not defined
    at transporter.sendMail (/home/project/controllers/signup.js:139:15)
    at transporter.send.args (/home/project/node_modules/nodemailer/lib/mailer/index.js:226:21)
    at callback (/home/project/node_modules/nodemailer/lib/sendmail-transport/index.js:90:28)
    at ChildProcess.sendmail.once.code (/home/project/node_modules/nodemailer/lib/sendmail-transport/index.js:131:28)
    at Object.onceWrapper (events.js:286:20)
    at ChildProcess.emit (events.js:198:13)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)
[nodemon] app crashed - waiting for file changes before starting...

这个 resolve(mail) 的使用方式不合法吗?

let mail = await new Promise((resolve,reject)=>{
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        console.log(error);
        reject(error);
    } else {
        res.status(200).json({ "success": true, "message": 'Thank you for your registration! We\'ve sent you an email to confirm!' });
        // change below
        resolve(info);
    }
  });
});

以上内容应该适用于您使用传递给 sendMail 回调的 info 进行解析。

否则你传递的邮件 未定义,只需将其替换为 info

else {
    res.status(200).json({
          success: true,
          message: 'Thank you for your registration! We\'ve sent you an email to confirm!'
     });
     resolve(info);
    }