首页 > 解决方案 > 解决错误 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"
}

标签: javascriptnode.jsarraysforeachreduce

解决方案


看起来您正在 foreach() lambda 表达式中访问 MonthlyArray。但是 MonthlyArray 实际上是由该 foreach() 的结果初始化的,因此您确实在对其进行初始化之前访问了 MonthlyArray。

这可能不是您想要的,但您发送响应的代码部分位于 lambda 表达式内。

很难看到,因为代码的缩进使得很难理解 lambda 表达式的结尾在哪里。

代码的适当缩进很可能会使其显而易见。


推荐阅读