我正在尝试使用nodemailer
根据数据库中的条目发送电子邮件。我已经尝试了几乎可以想到的所有方法(手动创建Promises
的数组,并在Promise.all()
的调用中使用它,使用map
进行此操作,等等),但是我总是继续出现相同的错误:UnhandledPromiseRejectionWarning: Error: Message failed: 450 SQLITE_ERROR: cannot start a transaction within a transaction
。 nodemailer
文档清楚地指出,当不传递callback-fn时,transporter.sendMail()
函数被包装为一个Promise。但是,当我像这样手动定义这些promise的数组时...
const transporter = nodemailer.createTransport(serverData);
const mailData = ...;
const arr = [transporter.sendMail(mailData), transporter.sendMail(mailData)];
...即使我还没有使用Promise.all()
遍历该数组,也已经触发了相同的错误;是否只有在我手动指定时才运行数组中的函数,这是一个误解?
无论如何,这是我完整的数据库代码;我正在使用sequelize
从数据库中检索数据。我已经验证了从该数据库的数据库侧获取数据没有问题。
class Mail extends Model {
...
static resendUndeliveredMails(){
this.findAll()
.then((mails) => {
return Promise.all(mails.map(async mail => {
transporter.sendMail(mail.dataValues);
}));
})
.catch((e) => {
console.log(e);
});
}
}
任何帮助将不胜感激!预先谢谢您:)。
答案 0 :(得分:1)
我已经用promise.all测试了nodeMailer API,但我没有发现任何问题,这是我在下面使用的代码,而另一件事是您收到的错误是与均衡器或SQL相关的错误导致的 SQLITE_ERROR UnhandledPromiseRejectionWarning: Error: Message failed: 450 SQLITE_ERROR: cannot start a transaction within a transaction
引发了错误,另一件事是您在promise中编写异步方法,我认为这是错误的,我将在此处与您分享编写函数的方式,但是关于您在运行promise之前触发promise的第一个问题。所有这些就是创建像[promise(arg)]
这样的Array时,您正在调用该函数,这样promise将启动,node会处理它,即使你不会把它放在promise.all
static async resendUndeliveredMails() {
try {
const mails = await findAll();
const mailerPromises = mails.map((mail) => transporter.sendMail(mail.dataValues));
const responses = await Promise.all(mailerPromises);
console.log(responses, "All Mails Have Been Sent Successfully");
} catch (e) {
console.log(e);
}
}
const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: "user",
pass: "pass", // naturally, replace both with your real credentials or an application-specific password
},
});
const mailOptions = {
from: "user@gmail.com",
to: "test@gmail.com",
subject: "testing due",
text: "Dudes, we really need your money.",
};
const mailOptions2 = {
from: "user@gmail.com",
to: "test1@gmail.com",
subject: "LOL due",
text: "Dudes, we really need your money.",
};
Promise.all([
transporter.sendMail(mailOptions),
transporter.sendMail(mailOptions2),
])
.then((res) => console.log(res))
.catch((err) => console.log(err));