Reputation: 105
I'm trying to get the name value from this promise from firebase firestore database:
(as for information I have a places colection that have a place containing a name and a ownerReference that references an owner document containing a name only.)
var names: any = [];
this.props.places.snapshot.docs.forEach((doc : any) => {
const place = doc.data()
place.ownerReference.get().then((snap : any) => {
name.push(snap.data().name);
console.log(names);
})
});
console.log(names);
the first console log return the desired data, the last one returns an empty object, I know this is happening because of the asynchronous nature of a promise , but how can I get the desired value assigned to this variable?
Upvotes: 1
Views: 1923
Reputation: 317467
Collect all the promises from each get()
into an array, then use Promise.all() to wait until they are all done. Iterate the resulting snapshots in the callback after that.
const promises = []
this.props.places.snapshot.docs.forEach((doc : any) => {
const place = doc.data()
promises.push(place.ownerReference.get())
})
Promise.all(promises).then(snapshots => {
const names = []
snapshots.forEach(snapshot => {
names.push(snapshot.data().name)
})
console.log(names); // this prints what you want
})
Upvotes: 2