如何避免嵌套的承诺从 Firestore 读取并等待所有解决?

How to avoid nested Promises to read from Firestore and wait for all resolve?

问题

如何修复嵌套的 Promise 并解析所有 Promise?

我正在读取三个 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));
  });
});