Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6213

firestore async await foreach vs for

$
0
0

I am using firestore for a while now, I want to implement a call to get data from a subcollection.

I had to create a asynchronous call and foreach() method did not await the call and continued, but it worked with the for() method. Can someone please explain to me why for() waits and foreach() doesn't?

Foreach() - doesn't work

export const FirebaseSearchUsers = async (search: string) => {  const end = search.replace(/.$/, c => String.fromCharCode(c.charCodeAt(0) + 1));  let users: UserDocument[] = [];  await firestore()    .collection(FirebaseConstraints.UserCollection)    .where('username', '>=', search)    .where('username', '<', end)    .limit(10)    .get()    .then(async x => {      x.forEach(async y => {        let userDocument: UserDocument = y.data() as UserDocument;        userDocument.houseInvites = [];        await y.ref          .collection(FirebaseConstraints.HouseInvitesCollection)          .get()          .then(x => x.forEach(x => userDocument.houseInvites.push(x.data() as HouseInviteDocument)));        users.push(userDocument);      });    });  return users;};

For() -works

export const FirebaseSearchUsers = async (search: string) => {  const end = search.replace(/.$/, c => String.fromCharCode(c.charCodeAt(0) + 1));  let users: UserDocument[] = [];    await firestore()    .collection(FirebaseConstraints.UserCollection)    .where('username', '>=', search)    .where('username', '<', end)    .limit(10)    .get()    .then(async x => {      for (let y of x.docs) {        let userDocument: UserDocument = y.data() as UserDocument;        userDocument.houseInvites = [];        await y.ref          .collection(FirebaseConstraints.HouseInvitesCollection)          .get()          .then(x => x.forEach(x => userDocument.houseInvites.push(x.data() as HouseInviteDocument)));        users.push(userDocument);      }    });  return users;};

Viewing all articles
Browse latest Browse all 6213

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>