node.js - 节点 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
如何在外面访问它
解决方案
你需要这样的东西。
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);
});
});
推荐阅读
- c# - 如何找到导致 System.Reflection.Assembly.LoadFile 失败的确切原因?
- regex - 货币的正则表达式 - 缺少一个条件
- javascript - 如何从 Instagram 上打开的页面向 whatsapp 发送消息
- node.js - 路由结构中的reactjs嵌套节点
- json - 在 Flutter 中解码 JSON 错误,类型 '(dynamic) => Null' 不是类型 '(String, dynamic) => void' of 'f' 的子类型
- rust - 有没有办法在 bevy 游戏引擎中检测 Sprites 的碰撞?
- vba - MS Access 2016 - 如果语句返回不正确的值
- graph - 在更大的图中搜索节点的几何配置的特定算法
- java - java打印流到页面文件
- .htaccess - 在移动设备上找不到网页 - 404