从 Firestore 获取数据时使用 async forEach 循环

Roc*_*boa 5 node.js async-await firebase google-cloud-firestore

我的 firestore 数据有点像这样:

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

我正在使用 nodejs 来获取我的数据,我还想显示发送此消息的人的电子邮件地址和姓名。所以我使用以下功能:

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 }))
});
Run Code Online (Sandbox Code Playgroud)

这里的日志顺序是:采集数据、发布数据、推送数据

我想要这样的顺序:收集数据,推送数据(x 次),发布数据

Roc*_*boa 6

我在@estus评论的帮助下解决了我的答案。

信用:@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)
}
Run Code Online (Sandbox Code Playgroud)

它非常轻松地解决了我的问题。


Shu*_*ary 5

使用以下代码:

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 }))
});
Run Code Online (Sandbox Code Playgroud)

或者

使用可以使用

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

promise.then(() => {
  console.log("posted");
  return res.status(200).end(...);
})
Run Code Online (Sandbox Code Playgroud)