无法解决承诺拒绝并发送数组作为响应

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

我正在尝试相互处理两个查询。

exports.get_users = (req, res) => {

  SubscriptionPlan.find()
    .then((result) => {
      if (!result) {
        return res.status(400).json({ message: "unable to process" });
      }
      let modifiedData = [];
      result.forEach(async (data) => {
        if (data.processStatus === "active") {
          await Users.findById(data.userId).then(
            (response) => {
              console.log(response)
              modifiedData.push(response);
              res.json(modifiedData)
            }
          );
        }
      });
    })
    .catch((err) => console.log(err));
};

我的问题是,如果我采用这种方法,那么我将得到诺言拒绝的错误:

node:15036) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)

而且,我在邮递员中收到的modifiedData数组的响应,只有长度为3的数组中的单个对象。语句console.log(response)返回3个需要推入新数组的对象。

如果我这样更改代码以解决拒绝问题,

exports.get_users = (req, res) => {

  SubscriptionPlan.find()
    .then((result) => {
      if (!result) {
        return res.status(400).json({ message: "unable to process" });
      }
      let modifiedData = [];
      result.forEach(async (data) => {
        if (data.processStatus === "active") {
          await Users.findById(data.userId).then(
            (response) => {
              console.log(response)
              modifiedData.push(response);
            }
          );
        }
      });
      res.json(modifiedData)
    })
    .catch((err) => console.log(err));
};

它返回一个空数组作为邮递员的响应。我知道我陷入了JS的异步本质之间,但是无法解决此问题。

PS。使用异步等待对我没有帮助。

任何早期帮助将不胜感激。

javascript arrays mongodb asynchronous es6-promise
1个回答
2
投票
result.forEach返回承诺数组。您需要使用Promise.all([])一次全部散布

exports.get_users = (req, res) => { SubscriptionPlan.find().then(async (result) => { if (!result) { return res.status(400).json({ message: "unable to process" }); } let modifiedData = []; await Promise.all( result.map(async(data) => { if (data.processStatus === "active") { const response = await Users.findById(data.userId); modifiedData.push(response); } }) ); return res.json(modifiedData); }).catch((err) => console.log(err)); };

或可以一次找到

exports.get_users = async (req, res) => { try { const result = await SubscriptionPlan.find({ processStatus: "active" }); if (!result) { return res.status(400).json({ message: "unable to process" }); } const ids = result.map(({ userId }) => userId); const response = await Users.find({ userId: { $in: ids } }); return res.json(response); } catch (err) { console.log(err) return res.status(400).json({ message: "unable to process" }); } };

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