javascript - 使用 map 或 foreach 进行异步/等待

标签 javascript node.js reactjs

我正在尝试从数据库中检索一堆产品价格,并假设我可以通过它们进行映射或查找,并将价格 += 到变量上,如下所示:

// 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 在 map 和数据库查找 promise 完成之前运行的问题。

感谢任何指导。

最佳答案

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

// 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));
};

关于javascript - 使用 map 或 foreach 进行异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60634777/

相关文章:

javascript - 如何从node.js调用JSON中的数组字段

javascript - 如何在 john resig 的高级 JavaScript 教程中定义 'assert'

javascript: 需要 ('events' ).EventEmitter;

node.js - 当我使用 throw 语句时,有什么方法可以改变错误消息的颜色吗?

node.js - Heroku 键 "Cannot read property ' 运行“未定义”

javascript - 如何处理 "outside"单击 Dialog (Modal)?

使用 ReactDOMServer 和 insideHTML 时,JavaScript 函数调用在表格下拉列表中不起作用

javascript - 无法使用 redux-form 找到商店

javascript - 我如何实现像 stackoverflow 快速搜索那样的 "help text"?

javascript - 单击按钮时更改选项卡