【发布时间】:2020-03-02 23:43:05
【问题描述】:
云函数中的等待/异步模式非常新。具有从具有 DocumentReferences 数组的文档中获取数据的云函数
/* Create new Chilla for a given date */
exports.createNewSalikChilla = functions.https.onRequest(async (req, res) => {
const email=req.body.email;
const date=req.body.date;
console.log('Creating chilla for Salik <' + email + '> on <' + date + '>');
const db = admin.firestore();
const habits = [];
const salikRef = db.collection('saliks').doc(email);
const salik = await salikRef.get();
if (!salik.exists) {
throw new Error("Salik not found for <" + email + ">");
}
const assignedHabits = salik.data()['assigned_habits'];
assignedHabits.forEach(element => {
//LOST on how to get these Document Reference and push to habits = []
});
res.send({status: "Success"});
});
saliks 集合中的文档在 firestore 上具有以下结构
assigned_habits<array>:
0:
habit<reference>: /habits/first
required<number>: 200
1:
habit<reference>: /habits/second
required<number>: 4
name: "Hani Q"
但是已经尝试了所有方法,但似乎无法弄清楚如何在这里使用 async/await 从数组中获取所有 DocumementReferecnce 并推送到 Habit Array,然后在完成后我发回 res.send({status : "成功"});
回答
在实施接受的答案后,以下工作
const assignedHabits = salik.data()['assigned_habits'];
const habits_data = (await Promise.all(assignedHabits.map(element => element.habit.get())))
.map(snapshot => snapshot.data());
console.log(habits_data);
res.send({status: habits_data});
【问题讨论】:
标签: node.js google-cloud-firestore async-await google-cloud-functions