简体   繁体   中英

Trying to understand why this "while" loop doesn't work as expected in React/JSX/node?

Simple problem that I haven't found a solution to. Trying to read a variable found inside a Firebase document "NumberOfQuestionsInList" starting with list 1 and going to the value of "Maximum". At first attempted a simple solution like below, however the while loop doesn't act in synchronous order and therefore the while loop continues increasing without ever calling the .get() function:

let booleanValue = false;

while(booleanValue===false){

    const QListDirectory = firestore.collection("content").doc(`List${i}`);

        QListDirectory.get().then((docSnapshot) => {

            if (docSnapshot.exists) {

                    QListDirectory.onSnapshot((doc) => {

                        let NumberInList= doc.data().NumberOfQuestionsInList;
                        

                        //Series of if, else if statements depending on the value of the "NumberInList".
                        //These if(), else if() statements contain commands to change "booleanValue" to true.
                        //when other conditions are met.


                     });
            }

   });

//Iterate over i, moving from List1, to List2 and so on....
i=i+1;

}

What I end up observing is just a while loop that continues to increase i by 1 and never appears to actually .get() and of the Firebase document information. Any clarity as to why a while loop like this isn't allowed would be greatly appreciated.

What is happening here is that you have the get of the promise that reads to the firestore taking some time and since you have more code to run (the i=i+1; ) outside of the promise you are just skipping the portion of the .then((docSnapshot) completely. Here you can see the anatomy of a promise

What you should do is first add a catch for that promise which is a really important part of a promise, and then move that i=i+1; inside of your your promise and also include it in your catch section so in case of an exception the loop continues.

Another possible solution here is to change from promises to async and declare your function as an async function, then you can use something like this

async function myloop() {
    const QListDirectory = firestore.collection("content").doc(`List${i}`);
    
    const docSnapshot = await QListDirectory.get();
    return docSnapshot.get("NumberOfQuestionsInList");        
}

This may not be the exact code that you need since you have multiple things to do that are redacted but this gives you an idea of another possible solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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