我正在尝试使用template_subject
变量作为subject
来发送电子邮件。
当我使用 findOne
从 mongodb 提取数据并设置变量 template_subject
时。它只是给了我值未定义
。
我已经从各个方面对其进行了测试,数据完全来自后端,只是没有设置为变量
。
有人有解决办法吗?
exports.sendMailMsg = function (templateName, email) {
var nodemailer = require("nodemailer");
var template_subject;
var template_html;
Template.findOne({name: templateName}, function (err, template) {
template_subject = template.subject;
template_html = template.dataMsg;
});
//----- Email Options -----//
var mailOptions = {
from: "Xyz <foo@blurdybloop.com>", // sender address
to: email, // list of receivers
subject: template_subject, // Subject line
html: "<b>Hello,</b><br/><br/> You are successfuly Registered"
};
最佳答案
这是因为 findOne 函数是异步的,因此在获取结果时,mailOptions 变量已经定义。 所以也许你可以这样做:
exports.sendMailMsg = function (templateName, email) {
var nodemailer = require("nodemailer");
var template_subject;
var template_html;
Template.findOne({name: templateName}, function (err, template) {
template_subject = template.subject;
template_html = template.dataMsg;
//----- Email Options -----//
var mailOptions = {
from: "Xyz <foo@blurdybloop.com>", // sender address
to: email, // list of receivers
subject: template_subject, // Subject line
html: "<b>Hello,</b><br/><br/> You are successfuly Registered"
};
//Do all the processing here...
});
关于javascript - 无法在 find() 中设置和获取变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21573477/