【发布时间】:2019-08-24 22:44:03
【问题描述】:
我正在尝试循环并从 firestore 获取不同的文档。正如您在下面的代码中看到的那样,“文档 ID”由名为“cart”的数组提供。
我尝试过的编程逻辑是这样的,每次迭代中的while循环从firestore获取文档,在第一个“then”部分它保存它刚刚获得的数据,在第二个“then”它增加“i” ' 并执行下一个循环。
问题是 while 循环不等待该 get 请求完成。它只是不断循环和崩溃。
即使我以某种方式设法正确执行循环部分也是如此。我将如何管理程序的整体执行流程,以便只有在完成循环部分之后才会执行进一步的代码,因为下面的代码使用循环部分更新的购物车数组。
let i = 0
while (i < cart.length) {
let element = cart[i]
db.collection(`products`).doc(element.productID).get().then((doc1) => {
element.mrp = doc1.data().mrp
element.ourPrice = doc1.data().ourPrice
return console.log('added price details')
}).then(() => {
i++;
return console.log(i)
}).catch((error) => {
// Re-throwing the error as an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('unknown', error.message, error);
});
}
return db.collection(`Users`).doc(`${uid}`).update({
orderHistory: admin.firestore.FieldValue.arrayUnion({
cart,
status: 'Placed',
orderPlacedTimestamp: timestamp,
outForDeliveryTimestamp: '',
deliveredTimestamp: ''
})
}).then(() => {
console.log("Order Placed Successfully");
})
【问题讨论】:
标签: javascript firebase asynchronous promise google-cloud-firestore