未处理的诺言拒绝mongoose汇总。

问题描述 投票:0回答:1

我知道有多个帖子在处理类似类型的问题,但对我来说似乎都不适用。

在我的应用程序中,我需要从数据库中获取垂直条形图的图形数据。过滤是基于两个状态类型和 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 <Pending>而第二种方法则返回 Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:467:11)

任何帮助纠正这个问题的帮助是感激的:)

node.js mongoose highcharts aggregate
1个回答
1
投票

关于你的 第一 办法, Promise.all(iterable) 方法接收一个iterable作为输入。在你的例子中 fetch_leads_newfetch_leads_pending 已经返回了一个待定的 Promise 数组,类似于......的东西。[ Promise { <pending> }, Promise { <pending> } ].

所以,目前你传递的是一个数组与数组或待定的promise(Promise.all([fetch_leads_new, fetch_leads_pending]))至 Promise.all 函数,类似

Promise.all([[ Promise { <pending> }, Promise { <pending> } ], [ Promise { <pending> }, Promise { <pending> } ]])

所以我觉得你可以考虑有两个 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 错误

© www.soinside.com 2019 - 2024. All rights reserved.