首页 > 解决方案 > 节点 js for 循环无法访问它打印 undefiend 的变量

问题描述

我正在使用 Node js 并使用 sendmail 功能

我声明变量htmlVal我尝试在外部访问,但它只打印 undefiend

function myFunction(){
    var htmlVal;
    Report.find({}, function (err, reports) {
        if (err) return res.status(500).send("There was a problem finding the users.");
        for(let reportData of reports){
            User.find({name:reportData.name}, function (err, users) {
                if (err) return res.status(500).send("There was a problem finding the users.");
                for (let item of users) {
                    htmlVal = `<table width="100%" cellpadding="2" cellspacing="0" style="border-style:solid; border-width:1px; border-color:#000000;">
<tr width="100%" cellpadding="2" cellspacing="0">
<th style="text-align:center; border:1px solid #000; padding:10px;border-right:1px solid #000">Name</th>
</tr>
<tr width="100%" cellpadding="2" cellspacing="0">
<td style="text-align:center;padding:10px;border:1px solid #000">`+item.name+`</td>
</tr>
</table>`;
                }
            });
        }
    });

    console.log(htmlVal);

    const sendmail = require('sendmail')({
        silent:true, 
    })
    sendmail({
        from: 'mymail@gmail.com',
        to: 'mymail@gmail.com',
        subject: 'Attendance of the Day',
        html: htmlVal
    }, function(err, reply) {
        console.log(err && err.stack);
        console.dir(reply);
    })

}

我正在使用这个 htmlVal 发送电子邮件,但它只发送空

因为我无法在外面访问htmlVal

如何在外面访问它

标签: node.js

解决方案


你需要这样的东西。

let htmlVal;
async.series([
    function(callback) {
        Report.find({}, function (err, reports) {
            if (err) return res.status(500).send("There was a problem finding the users.");

            async.eachSeries(reports, function (value, key, callbackFE) {
                User.find({name:value.name}, function (err, users) {
                    if (err) return res.status(500).send("There was a problem finding the users.");
                    for (let item of users) {
                        htmlVal = `<html></html`;
                    }
                    callbackFE();
                });
            }, function (err) {
                if (err) console.error(err.message);
                callback(null, htmlVal);
            });
        });
    }], function(err, htmlVal) {
    console.log(htmlVal);

    const sendmail = require('sendmail')({
        silent:true, 
    })
    sendmail({
        from: 'mymail@gmail.com',
        to: 'mymail@gmail.com',
        subject: 'Attendance of the Day',
        html: htmlVal
    }, function(err, reply) {
        console.log(err && err.stack);
        console.dir(reply);
    });
});

推荐阅读