manyouuwx
manyouuwx

Reputation: 47

Await async firebase foreach?

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
          });


        });



})
}

Upvotes: 0

Views: 253

Answers (1)

helloitsjoe
helloitsjoe

Reputation: 6539

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

Upvotes: 2

Related Questions