javascript - 如何在从我的承诺/功能返回之前等待 forEach 完成
问题描述
角,火库
我有一个角度函数来从一个 firestore 集合中获取产品,然后我循环该查询的结果以从另一个集合中查找价格。
在从外部承诺和外部函数本身返回之前,我如何才能等到 forEach 的价格完成?
返回的结果包含一个产品数组,但每个产品的价格数组为空。
const products = await this.billingService.getProducts();
async getProducts() {
let result = [];
let product = {};
return this.db.collection(
'products',
ref => { ref
let query: Query = ref;
return query.where('active', '==', true)
})
.ref
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(async function (doc) {
product = doc.data();
product['prices'] = [];
await doc.ref
.collection('prices')
.orderBy('unit_amount')
.get()
.then(function (docs) {
// Prices dropdown
docs.forEach(function (doc) {
const priceId = doc.id;
const priceData = doc.data();
product['prices'].push(priceData);
});
});
});
result.push(product);
return result;
});
}
我也尝试过这种方法,但不确定如何访问结果
await this.billingService.getProducts().then(results =>
getProducts() {
const dbRef =
this.db.collection(
'products',
ref => { ref
let query: Query = ref; return query.where('active', '==', true)
});
const dbPromise = dbRef.ref.get();
return dbPromise
.then(function(querySnapshot) {
let results = [];
let product = {};
querySnapshot.forEach(function(doc) {
let docRef = doc.ref
.collection('prices')
.orderBy('unit_amount')
results.push(docRef.get())
});
return Promise.all(results)
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
}
解决方案
推荐阅读
- linux - Linux中的mmap() - 文件的一部分与整个文件
- java - 如何在 Gradle 构建期间从 Swaggerhub Api 生成 Java Pojo?
- django - 无法使用 WebsocketConsumer 在 Django 频道中获取登录用户
- firebase - 在颤振中的两个不同应用程序之间进行通信(通过同一网络本地连接)
- python - `:` 是如何解释的?
- f# - 将用户定义类型转换回元组
- javascript - 无法访问嵌套的 JSON 对象键:Typescript 中的值
- javascript - Laravel Ajax 文件上传
- r - 如何在 Azure 上以交互方式运行 Docker 容器
- c++ - 缩小 STL 向量的复杂性