Use async forEach loop while fetching data from firestore

自作多情 提交于 2020-06-16 07:57:28

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/53149138/use-async-foreach-loop-while-fetching-data-from-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!