javascript - 无法在 find() 中设置和获取变量值

标签 javascript node.js mongodb angularjs

我正在尝试使用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/

相关文章:

javascript - 如何在 Jquery Validate 中覆盖 errorClass

java - YUI 压缩器在构建时压缩和替换

javascript - 如何正确加载 SoundCloud JS SDK for Streaming?

node.js - 如何使用环回模型查询来查询嵌套对象?

mongodb symfony 用户身份验证?

json - 如何从Json文件导入MongoDb

javascript - jQuery事件回调只运行一次(类似Angular的框架开发)

javascript - 检索 token /创建费用 - Stripe

node.js - 安装 PWA npm 包失败, Angular 项目中出现 404 错误

node.js - 保持 Node JS 应用程序运行