0

This is my code, i'm getting the values printed in console, but it's not returning that value.

async function fetchData(uid) {                                           
  return firebase.firestore().collection('users_info')
         .where("uid","==",uid).get()
         .then( async function(querySnapshot) {
             var usr;         
             querySnapshot.forEach(async function(doc) {           
             usr = await doc.data().name;
             console.log(usr);
             return  usr;
         });      
    });       
}
vizsatiz
  • 1,780
  • 1
  • 13
  • 31
Harish
  • 84
  • 6

2 Answers2

1

Since you are using a forEach I am assuming you are dealing with more than one data item. In that case, it might be better to push them all into an array and return that. I am adding a slight modification of your snippet bellow. I think this should do the trick.

  async function fetchData(uid) {
    return firebase.firestore()
      .collection('users_info')
      .where("uid", "==", uid)
      .get()
      .then(async function(querySnapshot) {
        var usr = [];
        querySnapshot.forEach(async function(doc) {
           const temp = await doc.data().name);
          usr.push(await doc.data().name))
        });
      return usr;
    })
  }
Doug Stevenson
  • 268,359
  • 30
  • 341
  • 380
Zer0
  • 367
  • 1
  • 4
  • 15
0

Two things - first, you need to return a promise, if your function itself is doing async work that needs it's own callback to be continued from. See Return from a promise then().

Also, foreach is not necessarily used to return a collection of transformed values, which seems to be what you're trying to do there. I'd replace it with map if you can.

Bondolin
  • 2,536
  • 6
  • 30
  • 59