如何避免嵌套的Promises从Firestore中读取并等待所有解析?

渡边

问题

如何修复嵌套的承诺并解决所有承诺?

我正在从三个Firestore集合中读取数据,并通过已解析的数据进行一些计算。

消防站的结构

/users/userId
/purchases/purchaseId/
  - userId: string
  - initialPrice: number
  - productId: string
/products/productId
  - itemId: string
  - currentPrice: number

我想做的计算

为每个用户计算
Σ(currentPrice[i] - initialPrice[i])
,其中每个用户i有一个项目。

代码无效,需要修复

db.collections('users').get().then(snap => {
  snap.forEach(user => {
    const userId = user.id
    let totalProfit = 0

    db.collections('purchases').where('userId', '===', userId).get().then(snap =>{
      snap.forEach(purchase => {
        const initialPrice = purchase.initialPrice
        const productId = purchase.productId

        db.collections('products').doc(productId).get().then(doc => {
          const currentPrice = doc.currentPrice
          const profit = currentPrice - initialPrice
          totalProfit += profit
        })
      })
    })
    // Please wait for all Promises resolved.
    console.log(userId, totalProfit)
  })
})
亭子

收集内在的诺言并呼吁Promise.all他们。等待解决,然后致电console.log

db.collections('users').get().then(snap => {
  snap.forEach(user => {
    const userId = user.id;
    let totalProfit = 0;

    db.collections('purchases').where('userId', '===', userId).get().then(snap =>{
      const promises = [];
      snap.forEach(purchase => {
        const initialPrice = purchase.initialPrice;
        const productId = purchase.productId;

        promises.push(db.collections('products').doc(productId).get().then(doc => {
          const currentPrice = doc.currentPrice;
          const profit = currentPrice - initialPrice;
          totalProfit += profit;
        }));
      });
      return Promise.all(promises);
    }).then(() => console.log(userId, totalProfit));
  });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用roslyn构建和现有解决方案,并解析csproj中的所有引用,以便可以解析所有类型

如何读取/解析目录中的所有Yaml文件?

如何在列表视图中显示来自arraylist的所有解析数据?

如何等待所有动态嵌套承诺结束?

Beautiful Soup 没有解析所有标签

在Java中解析XML文件时,如何避免读取DTD?

如何从android的fireStore数据库中读取嵌套地图

如何在Firestore中读取嵌套的数组和地图?

在Android的一次通话中,有什么方法可以取消所有解析通道的订阅

在CloudWatch Insights中,如何过滤没有解析值的日志条目?

如何识别在Python中具有解析错误的文件名?

从文件中读取所有属性(也包括嵌套属性!)

是否会在ORC文件中读取所有嵌套的列?

如何在继续之前等待所有文件被读取并执行所有回调

如何將 CPLEX 中的所有解決方案獲取到 MIP

如何在Sympy中获得cos(x)* cosh(x)== 1的所有解?

解析所有嵌套值

石墨烯在上下文管理器中运行所有解析器

Java。我如何从BuffereReader值中删除所有行直到一个点,以避免对其进行解析?

Firebase Firestore 安全规则 - 根据资源读取所有嵌套文档(但为空)

ES6 JS Promises-如何避免条件嵌套

告诉 forEach 等待,并且主要避免将所有内容包装在异步函数中以使用等待?

如何删除具有解析数据的单元格?

Coq 中的范围 - 没有解析就导入?

如何获得拓扑排序的所有解决方案

Promises中Promises中嵌套回调中的Node.js Promises无法解析

如何等待所有商店在ExtJs中同步?

如何等待所有动画在jQuery中完成?

如何等待所有Promise在ExpressJS中解决?