Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use async forEach loop while fetching data from firestore

I have firestore data somewhat like this:

"Support": { "userid":"abcdxyz", "message": "hello" }

I am using nodejs to fetch my data and I also want to show the email address and name of the person who sent this message. So I am using following function:

database.collection("support").get().then(async function (collections) {
var data = [];
console.log("data collected");
collections.forEach(async function (collection) {
    var temp = {};
    var collectionData = collection.data()
    var userInfo = await getUserDetails(collectionData.userId)
    temp.name = userInfo.name
    temp.supportMessage = collectionData.supportMessage
    data.push(temp)
    console.log("data pushed")
});
    console.log("data posted")
    return res.status(200).end(JSON.stringify({ status: 200, message: "Support Message fetched successfully.", data: data }))
}).catch(error => {
    return res.status(500).end(JSON.stringify({ status: 500, message: "Error: " + error }))
});

Here the sequence of logs is following: data collected, data posted, data pushed

I want the sequence like this: data collected, data pushed (x times), data posted

like image 241
Rocky Balboa Avatar asked Nov 05 '18 06:11

Rocky Balboa


2 Answers

Use following code:

database.collection("support").get().then(async function (collections) {
var data = [];
console.log("data collected");

for await(let collection of collections){
  var temp = {};
  var collectionData = collection.data()
  var userInfo = await getUserDetails(collectionData.userId)
  temp.name = userInfo.name
  temp.supportMessage = collectionData.supportMessage
  data.push(temp)
  console.log("data pushed")
}

console.log("data posted")
return res.status(200).end(JSON.stringify({ status: 200, message: "Support Message fetched successfully.", data: data }))
}).catch(error => {
  return res.status(500).end(JSON.stringify({ status: 500, message: "Error: " + error }))
});

OR

Use can use

var promise = Promise.all(collections.map((collection) =>{
   ...
   return await ... //or a promise
}));

promise.then(() => {
  console.log("posted");
  return res.status(200).end(...);
})
like image 141
Shubham Chaudhary Avatar answered Nov 18 '22 02:11

Shubham Chaudhary


I solved my answer with the help of @estus comment.

Credit: @estus

var data = [];
var tempCollection = [];
collections.forEach(collection => {
    tempCollection.push(collection.data());
});
for (collection of tempCollection) {
    var temp = {};
    var userInfo = await getUserDetails(collection.userId)
    temp.name = userInfo.name
    temp.supportMessage = collection.supportMessage
    data.push(temp)
}

It solved my problem very easily.

like image 5
Rocky Balboa Avatar answered Nov 18 '22 04:11

Rocky Balboa