javascript - 解决错误 500;“初始化前无法访问‘对象’”}
问题描述
寻求有关如何解决此错误的帮助。我正在尝试根据每个月内发生的交易总和来获得一系列每月交易总和。
下面是我的代码,
exports.monthlyTotalArray = async (req, res) => {
const { userId } = req.body;
const requestMonths = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const today = new Date();
var relevantYear = today.getYear();
try {
return await Transaction.findAll({
where: {
userId: userId,
},
}).then((transactions) => {
if (transactions.length == 0) {
res.status(401).json({
message: { msgBody: "No transactions found", msgError: true },
});
} else {
const MonthlyArray = requestMonths.forEach((requestMonth) => {
transactions
.filter((i) => {
const date = new Date(i.date);
return (
date.getMonth() == requestMonth &&
date.getYear() == relevantYear
);
})
.reduce((prev, curr) => prev + parseFloat(curr.amount), 0);
res.status(200).send({
MonthlyArray,
});
});
}
});
} catch (error) {
res.status(500).send({
message: error.message || "some error occurred",
});
}
};
当我尝试运行代码时出现此错误
{
"message": "Cannot access 'MonthlyArray' before initialization"
}
解决方案
看起来您正在 foreach() lambda 表达式中访问 MonthlyArray。但是 MonthlyArray 实际上是由该 foreach() 的结果初始化的,因此您确实在对其进行初始化之前访问了 MonthlyArray。
这可能不是您想要的,但您发送响应的代码部分位于 lambda 表达式内。
很难看到,因为代码的缩进使得很难理解 lambda 表达式的结尾在哪里。
代码的适当缩进很可能会使其显而易见。
推荐阅读
- python - Python,将用户输入存储在一个数组中,然后将它们打印在一首诗中
- jquery - 我如何从以下列表视图中选择按钮单击时的 val() ,
- ubuntu - pandoc无法在ubuntu中将表从markdown转换为epub
- python-3.x - Python 请求使用证书值而不是路径
- javascript - 如何将数据从 C# 传递到 javascript 函数?
- kdb - .Q.hg 因协议不可用错误而失败
- c++ - 我如何计算字数?
- c++ - 为什么我不能取消引用这个迭代器?
- c++ - 理解带有位移的右移运算符
- elasticsearch - 如何从具有特定请求值的搜索查询中排除结果?