0

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?

1 Answer 1

1

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)
})
Sign up to request clarification or add additional context in comments.

1 Comment

I got empty on docs, it doesn't give any result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.