【问题标题】:Unhandled promise rejection mongoose aggregate未处理的承诺拒绝猫鼬聚合
【发布时间】:2020-10-04 20:09:07
【问题描述】:

我知道有多个帖子处理类似类型的问题,但似乎没有一个适合我。

在我的应用程序中,我需要从我的数据库中获取垂直条形图的图形数据。过滤基于两种状态类型和 updatedAt 字段。将为一年中的每个月绘制数据。

我尝试了两种相同的方法:

第一:

exports.leads_based_on_status = async (req, res) => {
  const { userId } = req.user;
  const fetchMonths = getMonths();

  try {
    const fetch_leads_new = await fetchMonths.map(async (month) => {
      return Lead.aggregate([
        {
          $match: {
            userId: mongoose.Types.ObjectId(userId),
          },
        },
        {
          $unwind: "$leads",
        },
        {
          $match: {
            $and: [
              { updatedAt: { $gt: month._start, $lt: month._end } },
              { "leads.status": "New" },
            ],
          },
        },
      ]);
    });

    const fetch_leads_pending = await fetchMonths.map(async (month) => {
      return Lead.aggregate([
        {
          $match: {
            userId: mongoose.Types.ObjectId(userId),
          },
        },
        {
          $unwind: "$leads",
        },
        {
          $match: {
            $and: [
              { updatedAt: { $gt: month._start, $lt: month._end } },
              { "leads.status": "Pending" },
            ],
          },
        },
      ]);
    });

    Promise.all([fetch_leads_new, fetch_leads_pending]).then(
      (resultnew, resultpending) => {
        console.log("show result new", resultnew);

        console.log("show result pending", resultpending);

        //both these results in Promise <pending>
      }
    );

    const leads_status_statics = [
      {
        New: fetch_leads_new,
      },
      {
        Pending: fetch_leads_pending,
      },
    ];
    res.status(200).json({ message: "Graphical Data", leads_status_statics });
  } catch (error) {
    console.log(error) || res.status(500).json({ error });
  }
};

第二:

exports.leads_based_on_status = async (req, res) => {
  const { userId } = req.user;
  const fetchMonths = getMonths();

  try {
    fetchMonths.map(async (month) => {
      const fetch_leads_new = await Lead.aggregate([
        {
          $match: {
            userId: mongoose.Types.ObjectId(userId),
          },
        },
        {
          $unwind: "$leads",
        },
        {
          $match: {
            $and: [
              { updatedAt: { $gt: month._start, $lt: month._end } },
              { "leads.status": "New" },
            ],
          },
        },
      ]);

      const fetch_leads_pending = await Lead.aggregate([
        {
          $match: {
            userId: mongoose.Types.ObjectId(userId),
          },
        },
        {
          $unwind: "$leads",
        },
        {
          $match: {
            $and: [
              { updatedAt: { $gt: month._start, $lt: month._end } },
              { "leads.status": "New" },
            ],
          },
        },
      ]);

      const leads_status_statics = [
        {
          New: fetch_leads_new,
        },
        {
          Pending: fetch_leads_pending,
        },
      ];
      res.status(200).json({ message: "Graphical Data", leads_status_statics });

      //de:16484) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    });
  } catch (error) {
    console.log(error) || res.status(500).json({ error });
  }
};

但是他们都不能帮助我解决我的问题。第一种方法不断返回Promise &lt;Pending&gt;,而第二种方法返回Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:467:11)

感谢您帮助解决问题:)

【问题讨论】:

  • Cannot set headers after they are sent to the client 表示您多次发送请求响应!检查你的代码。
  • @AnaLava 在我的第二种方法中,我只发送一个 res.json()
  • 在您的发送方法中,如果fetchMonths 有多个条目,这意味着res.status(200).json(... 也被多次调用(在map 函数的每次迭代中)如上所述
  • @Vishnu 第一种方法怎么样?你能帮我理解未决承诺的原因吗?

标签: node.js mongoose highcharts aggregate


【解决方案1】:

关于您的第一种方法,Promise.all(iterable) 方法将可迭代对象作为输入。在您的情况下,fetch_leads_newfetch_leads_pending 已经返回一个待处理的 Promise 数组,例如 :[ Promise { &lt;pending&gt; }, Promise { &lt;pending&gt; } ].

因此,目前您正在将带有数组或待处理 promise(Promise.all([fetch_leads_new, fetch_leads_pending])) 的数组传递给 Promise.all 函数,类似于

Promise.all([[ Promise { &lt;pending&gt; }, Promise { &lt;pending&gt; } ], [ Promise { &lt;pending&gt; }, Promise { &lt;pending&gt; } ]])

所以我认为您可以考虑使用两种Promise.all 方法,其中一种用于fetch_leads_new,另一种用于fetch_leads_pending

const newRecords = await Promise.all(fetch_leads_new);
const pendingRecords = await Promise.all(fetch_leads_pending);

const leads_status_statics = [
  {
    New: newRecords,
  },
  {
    Pending: pendingRecords,
  },
];

关于第二种方法

fetchMonths 有多个条目时,这意味着res.status(200).json(... 也被多次调用(在map 函数的每次迭代中),这就是为什么您会收到Cannot set headers after they are sent to the client 错误

【讨论】:

  • 感谢您的澄清 :)
猜你喜欢
  • 2021-05-24
  • 1970-01-01
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
  • 2023-03-17
  • 2018-04-01
相关资源
最近更新 更多