0

Im trying to get the document ID for places and and review that is referenced on one of the subcollection on my 'users' collection. After getting it i perform another query to then use those IDs to get the actual value of the review field which is in another collection 'places'

    var query = db.collection('users/ziRsQGzbuwVp805SYY9vkZIbbJ93/myRecommendations');
        query.get().then(function(querySnapshot){
        querySnapshot.forEach(function(doc){
            locData.placeID = doc.data().placesDocument;
            locData.reviewID = doc.data().reviewDocument;
            var query2 = db.collection('places').doc(locData.placeID).collection('reviews').doc(locData.reviewID)
            query2.get().then(function(doc){
                locData.review = doc.data().specRemarks         
                locdataArr.push(parse)
                console.log(locdataArr)

however, the foreach from the first query

        querySnapshot.forEach(function(doc){
            locData.placeID = doc.data().placesDocument;
            locData.reviewID = doc.data().reviewDocument;
            var query2 = db.collection('places').doc(locData.placeID).collection('reviews').doc(locData.reviewID)
            query2.get().then(function(doc){
                locData.review = doc.data().specRemarks

seems to loop before doing the second query which leads to only the last output from the first query going through the second with these output from the log

enter image description here

the review was successful (one value is actually null in the firestore and the other was TEsting/n) but the recorded IDs were only from the last output of the first query. How should i fix this?

1 Answer 1

1

What you're observing is what I would expect. Since get() is asynchronous and returns a promise, it will always return immediately, before the results of the query are available. If you put a bunch of calls to get() in a loop, the loop will always complete before any of the results of the async work is complete.

If you want to wait until a bunch of promises are resolved, you should collect them into an array and use Promise.all() to create another promise that resolves when all of them are complete.

See also:

2
  • Thanks for the answer. I now understand the concept of promises but i can't seem to wrap my head as to how am i supposed to apply it on my current code. Do you mind if you could give hints as to what i should do Commented Mar 12, 2020 at 20:12
  • The other questions I linked to have specific examples. Commented Mar 12, 2020 at 20:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.