如何修复嵌套的承诺并解决所有承诺?
我正在从三个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] 删除。
我来说两句