繁体   English   中英

在 foreach 循环后数组为空(异步/等待)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM