3 回答
TA贡献1777条经验 获得超10个赞
让 getProducts() 函数成为一个承诺。因此,只有当您解决它(或拒绝它)时它才会返回。
getProducts() {
return new Promise((resolve,reject)=> {
let result = [];
let product = {};
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'] = [];
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);
});
resolve(result);// returns when it reaches here
});
});
result.push(product);
});
})
}
然后你可以使用 then 或await 来调用promise
this.billingService.getProducts().then( res => {
const products = res;
})
使用等待
const products = await this.billingService.getProducts();
TA贡献1872条经验 获得超3个赞
此版本的代码有效:
getProducts(): Promise<any> {
return new Promise((resolve,reject)=> {
let result = [];
let product = {};
this.db.collection(
'products',
ref => { ref
let query: Query = ref;
return query.where('active', '==', true)
})
.ref
.get()
.then(async function (querySnapshot:firebase.firestore.QuerySnapshot) {
for(const doc of querySnapshot.docs) {
const priceSnap = await doc.ref
.collection('prices')
.orderBy('unit_amount')
.get()
product = doc.data();
product['prices'] = [];
// Prices dropdown
for(const doc of priceSnap.docs) {
const priceId = doc.id;
let priceData = doc.data();
priceData['price_id'] = priceId;
product['prices'].push(priceData);
resolve(result);// returns when it reaches here
};
result.push(product);
};
});
})
}
添加回答
举报