Jack Venevankham
Jack Venevankham

Reputation: 167

Can't push data from firebase to array by using foreach in Node.js

I tried to fetch data from firebase firestore, which I get what I wanted by console.log(). But when I tried to store what I get to array using push(). It gives me empty value in return. Here is my code:

app.post('/getMemberInfo', async (req, res) => {
  var memberKeyList = req.body.member
  var memRef = await db.collection("user")
  let newArray = []
  memberKeyList.forEach((row) => {
    memRef.doc(row.MemberID).get().then((doc)=>{

        newArray.push(doc.data())
        console.log(doc.data())

      

    })
    
  })
  res.send(newArray)
})

Here on console.log I got all data, but in newArray it returns empty array. What did I do wrong here? Any solution?

Upvotes: 0

Views: 96

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598976

The problem is that each get() call is an asynchronous operation, and your res.send(newArray) runs before any of these calls complete (which you can see by adding some more logging and checking the order of the output).

The solution is to use Promise.all to wait for all the asynchronous operations to complete before sending the result back to the client:

app.post('/getMemberInfo', async (req, res) => {
  var memberKeyList = req.body.member
  var memRef = await db.collection("user")
  let newArray = []
  const docs = Promise.all(memberKeyList.map((row) => memRef.doc(row.MemberID).get()));
  const newArray = docs.map((doc)=> doc.data());
  res.send(newArray)
})

Upvotes: 1

Related Questions