Reputation: 19
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
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?
Upvotes: 0
Views: 390
Reputation: 317372
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:
Upvotes: 1