0

i want to wait for the getAnswers value response from firebase and push it in the foreach array ! how can i do that ?

 async fetchData() {
    console.log('fetchdata')
    const UID = Firebase.auth().currentUser.uid;
    const ref = FirebaseRef.child('my_questions/' + UID + '/');
    // console.log(ref);
    ref
      .orderByKey()
      .limitToLast(this.state.limit)
      .once('value', snapshot => {
        var items = [];
        snapshot.forEach(child => {

          var getAnswers = await FirebaseRef.child('counter/questions/' + child.key + '/count_answers').once('value')



          items.push({
            key: child.key,
            ...child.val(),
            count_answers: getAnswers
          });


        });



})
}
robsiemb
  • 6,157
  • 7
  • 32
  • 46
manyouuwx
  • 47
  • 6

1 Answers1

2

You need to use Promise.all and .map instead of forEach:

const items = await Promise.all(snapshot.map(async (child) => {
  const getAnswers = await Firebase...
  ...

  return {
    key: child.key,
    ...child.val(),
    count_answers: getAnswers
  }
}))

See this answer for more detail: Use async await with Array.map

helloitsjoe
  • 6,264
  • 3
  • 19
  • 32
  • Since when do firebase snapshots support `map`? – Bergi May 31 '21 at 02:39
  • 1
    @Bergi Interesting... when I wrote this answer I didn't realize `snapshot` is a Firebase-specific data collection, I assumed this person was working with an array. Given that, I'm a little surprised this was marked as the correct answer, but you're right. `snapshot` doesn't support `map`. – helloitsjoe Jun 04 '21 at 11:46