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,933
  • 1
  • 17
  • 36
Harish
  • 104
  • 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
  • 297,357
  • 32
  • 422
  • 441
Zer0
  • 448
  • 1
  • 5
  • 16
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,793
  • 7
  • 34
  • 62