【问题标题】:Resolving error 500; "Cannot access 'object' before initialization" }解决错误 500; “初始化前无法访问‘对象’”}
【发布时间】:2020-12-09 14:51:00
【问题描述】:

寻求有关如何解决此错误的帮助。我正在尝试根据每个月内发生的交易总和来获得一系列每月交易总和。

下面是我的代码,

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的回调函数之外调用res.status(200)...send({ MonthlyArray })

标签: javascript node.js arrays foreach reduce


【解决方案1】:

主要问题是您在 requestMonths.forEach 的回调函数内部调用 res.send({ MonthlyArray }),这就是您收到错误的原因。

const MonthlyArray = requestMonths.forEach((requestMonth) => {
  // you're calling it here
  res.status(200).send({
    MonthlyArray,
  });
});
// instead, it should be here
res.status(200).send({
  MonthlyArray,
});

另外,您可能不想使用forEach,因为forEach 不会返回任何内容,所以MonthlyArray 将是undefined。相反,请使用Array.map 来获得您需要的结果。

if (transactions.length == 0) {
  // ...
} else {
  const MonthlyArray = requestMonths.map((requestMonth) => {
    return 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,
  });
}

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

    • 谢谢@sboisse
    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 2020-09-08
    • 2021-09-29
    • 2019-10-12
    • 2020-11-30
    • 2021-11-02
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多