任务:从数据库获取查询=>生成多个pdf =>通过节点js发送邮件附件 问题:这里的问题是在生成pdfs之前我调用了sendMail()函数。那么如何在生成所有pdfs之后调用sendMail函数?
pdfs = [];
// Pdf generate code
var generatePdf = function (rows) {
return new Promise(function (resolve, reject) {
for (var i = 0; i < rows.length; i++) {
html = ejs.renderFile(
'views/voucher.ejs',
{
voucher: rows[i]
},
function (error, success) {
if (error) {
console.log(error);
} else {
var pdf_path = '/srv/ voucher/uploads/voucher/' + Math.random().toString(36).substring(7) + '.pdf';
htmlToPdf.convertHTMLString(success, pdf_path, function (error, success) {
if (error) {
console.log('Oh noes! Errorz!');
console.log(error);
} else {
pdfs.push(pdf_path);
console.log("Single");
console.log(pdfs);
console.log('Woot! Success!');
}
});
}
});
}
resolve();
});
}
// send mail code
var sendMail = function () {
new Promise(function (resolve, reject) {
console.log("All" + pdfs);
pdfs.forEach(function (value, key) {
// mail sending code
});
});
};
var findVoucherAndSendMail = function () {
return new Promise(function (resolve, reject) {
var query = con.query('SELECT * FROM voucher limit 20', function selectAll(err, rows, fields) {
if (err) {
throw err;
}
resolve(rows);
});
});
};
findVoucherAndSendMail().then(function (fromResolve) {
return generatePdf(fromResolve);
}).then(function () {
return sendMail();
}).catch(function () {
});
答案 0 :(得分:1)
生成pdf时,您的问题链接到for循环中的异步行为。
在生成pdf之前,您的承诺已得到解决。
您应该使用Promise.all
等待代完成。
function generatePdf(rows) {
return Promise.all(rows.map(row => asyncPdfGeneration(row));
}
function asyncPdfGeneration(row) {
return new Promise(function (resolve, reject) {
...generate pdf
resolve(pdf);
}
}
答案 1 :(得分:0)
第二个&#39;然后&#39;在你的函数findVoucherAndSendMail()上,所以一旦findVoucherAndSendMail()完成,generatePdf()和sendMail()都会触发。
放置第二个&#39;然后&#39;在generatePdf()
findVoucherAndSendMail().then(function (fromResolve) {
return generatePdf(fromResolve).then(function () {
return sendMail();
});
}).catch(function () {
});
修改的
您是否尝试过:resolve(pdfs);
而非resolve();