3 回答

TA貢獻1807條經(jīng)驗 獲得超9個贊
根據(jù)評論發(fā)布為社區(qū) Wiki 答案。
對于這種情況,使用 aforEach()
不是正確的選擇。正如此處所澄清的那樣,無法forEach()
與await
函數(shù)正常工作,這樣,就無法與您的承諾正常工作。考慮到這一點以及您想要按順序讀取數(shù)據(jù)的事實 - 因為一個查詢的結(jié)果將影響第二個查詢 - 您需要使用普通 , 來循環(huán)for
數(shù)據(jù)和數(shù)組。

TA貢獻1777條經(jīng)驗 獲得超10個贊
讓 getProducts() 函數(shù)成為一個承諾。因此,只有當(dāng)您解決它(或拒絕它)時它才會返回。
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 來調(diào)用promise
this.billingService.getProducts().then( res => {
const products = res;
})
使用等待
const products = await this.billingService.getProducts();

TA貢獻1872條經(jīng)驗 獲得超4個贊
此版本的代碼有效:
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);
};
});
})
}
添加回答
舉報