forEach循环中的猫鼬诺言功能不起作用

时间:2019-08-10 20:20:49

标签: javascript node.js express mongoose

我正在使用Express和Mongoose在Node中编写一个网上商店。 猫鼬模型是“产品”和“项目”。每个项目都属于一个产品。我要计算产品的项目(库存)并将此信息提供给视图。

问题在于,在完成forEach循环之前执行了res.render部分。所以“ product.stock”是不确定的

exports.getProducts = (req, res, next) => {
    Product.find()
        .lean()
        .then(products => {

            products.forEach(product => {
                Item.countDocuments({productId: product._id})
                    .then( count => {
                        product.stock = count
                    })
            });

            res.render('shop/product-list', {
                path: '/products',
                pageTitle: "All Products",
                products: products
            })
        })
        .catch(err => { return next(err) })
};

1 个答案:

答案 0 :(得分:1)

尝试使用async / await

exports.getProducts = (req, res, next) => {
    Product.find()
        .lean()
        .then(async (products) => {
            await Promise.all(products.map(async (product) => {
                product.stock = await Item.countDocuments({productId: product._id});
            });

            res.render('shop/product-list', {
                path: '/products',
                pageTitle: "All Products",
                products: products
            })
        })
        .catch(err => { return next(err) })
};

我将forEach更改为map,以便将您的Product列表转换为Promise列表。然后Promise.all等待直到所有Promise完成,这将在为每个产品设置product.stock时发生。只有这样,res.render()才会被调用。

相关问题