[英]Array is empty after a foreach loop (async/await)
我正在嘗試為一個項目檢索一組卡片。 但是,在我的函數中,最終的contacts
數組返回一個空數組。 我知道,因為我在 forEach 循環中對另一個函數進行了異步調用,所以循環不會按預期執行。 但是,在處理這個問題時,我是個新手,所以我想問你處理這個問題的最佳方法是什么。 這是我的代碼:
export const extractsIDSForUser = async (currentUser: User) : Promise <Object> => {
let contactCards = currentUser.contacts;
const contacts = [];
const usersRef = await firebase.firestore().collection('Users').get();
const usersSnapshot = usersRef.docs.map(doc => doc.data());
contactCards.forEach(async folder => {
const ids = [];
folder.forEach(contact => {
ids.push(contact);
});
for (let i = 0; i < ids.length; i +=1) {
const contact = ids[i];
for (let j = 0; j < usersSnapshot.length; j += 1) {
const userId = usersSnapshot[j].id;
// Async call to function
const cardsFromUser = await extractCardsFromUser(userId);
const arrayCards = Object.values(cardsFromUser);
if (arrayCards.length > 0) {
for (let j = 0; j < arrayCards.length; j += 1) {
const arrayId = arrayCards[j].id;
const sameCardId = arrayId === contact;
if (sameCardId) {
// Where I insert the values into the array
contacts.push(arrayCards[j]);
}
}
}
}
}
});
// this is empty
return contacts;
}
處理這個問題的最佳方法是什么?
我想你已經找到了解決方案,但我遇到了類似的問題,發現這篇文章很有幫助。
您可以使用傳統for (const contactCard of contactCards)
並且它會起作用,但它會比使用Promise.all
方法效率低。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.