首页 > 解决方案 > 使用 map 或 foreach 进行异步/等待

问题描述

我试图从我的数据库中检索一堆产品价格,并假设我可以通过它们映射或 foreach 并将 += 价格映射到如下变量:

// Get Total
exports.getTotal = (req,res) => {
  let productList = req.body;
  let total = 0;

  const results = productList.map(async (product) => {
      Product.findById(product._id)
          .select('price')
          .exec((err, foundProduct) => {
              if (err){
                  console.log(`Error: Product with id ${product._id} not found.`);
              } else {
                  console.log('Product price. ', foundProduct.price);
                  total += foundProduct;
              }
          })
  });

  Promise.all(results).then(data => console.log('Total is', total));

};

但是,总数的 console.log 始终返回 0。我怀疑 console.log 在地图和数据库查找承诺完成之前运行是一个问题。

任何指导表示赞赏。

标签: javascriptnode.jsreactjs

解决方案


您以错误的方式使用 exec Exec 返回您一个承诺。你可以像这样简化这个

// Get Total
exports.getTotal = (req, res) => {
  const productList = req.body;
  let total = 0;

  const results = productList.map(async product => {
    const foundProduct = await Product.findById(product._id).exec();
    total += foundProduct;
    return foundProduct;
  });

  Promise.all(results).then(data => console.log("Total is", total));
};


推荐阅读