在使用 mongoose 和 express 进行多次异步查询后发送响应

Send response after multiple asynchronous queries with mongoose and express

我尝试列出发送给客户的产品,但 res.send 在循环完成之前执行。你有什么建议吗? Async/await 好像不行。

这是我的代码:

const Outfits = require("../models/Outfits");
const Products = require("../models/Products");

module.exports = (req, res) => {
    Outfits.find({ outfitId: req.params.id }, async (error1, result) => {
        if (error1) {
            res.status(400).json({
                status: "fail",
            });
        } else {
            let productIds = result[0].productIds;
            let productList = [];
            for (let i = 0; i < productIds.length; i++) {
                await Products.find({ id: productIds[i] })
                    .then((product) => {
                        console.log(product);
                        productList.push(product);
                    })
                    .catch((error2) => {
                        res.status(400).json({
                            status: "fail",
                        });
                    });
            }
            console.log(productList);
            res.status(200).json({
                status: "success",
                body: productList,
            });
        }
    });
};

非常感谢!

您需要像这样在 Products.find 函数上调用 await

for (let i = 0; i < productIds.length; i++) {
  try {
    const product = await Products.find({ id: productIds[i] }).exec()
    console.log(product);
    productList.push(product);
  } catch (error) {
    res.status(400).json({
      status: "fail",
    });
  }
}

为了同时执行多个异步任务,一种简洁的方法是使用 Promise.all 并传递一个异步任务数组。像这样:

const Outfits = require("../models/Outfits");
const Products = require("../models/Products");

module.exports = (req, res) => {
    Outfits.find({ outfitId: req.params.id }, async (error1, result) => {
        if (error1) {
            res.status(400).json({
                status: "fail",
            });
        } else {
            let productIds = result[0].productIds;
            
            //
            const productList = await Promise.all(
                 productIds.map((id) => Products.findById(id))
            );
           
            console.log(productList);
            res.status(200).json({
                status: "success",
                body: productList,
            });
        }
    });
};

Do you have any suggestions? Async/await doesn't seem to work

您的代码中的 async/await 不起作用,这是 因为 mongoose 为您提供的功能。

  1. 回调样式

    //找到服装并将服装传递给回调

    Outfits.find({ outfitId: req.params.id }, async (error1, outfit) => {

    //你的其他逻辑

    })

  2. async/await风格

    // 找到服装 returns

    const outfit = await Outfits.find({outfitId: req.params.id }).exec();

假设您以这种方式检索产品 ID 数组

let productIds = result[0].productIds;

const products = await Promise.all(

productIds.map((productId)=>{

   return Products.findById(productId)

}

)

这应该会为您检索产品列表

这是我第一次回答问题所以努力回答哈哈:)。