我想创建一个计划的云功能,该功能在每个月底产生员工奖金。为此,我需要列出所有员工,该用户的所有发票以及所有现有奖金的清单,所有清单都包含在Firestore集合中。因此,我需要3个Firestore集合,但找不到如何在云函数中查询的解决方案。
我暂时尝试过:
exports.generateBonus = functions.https.onRequest(async (req, res) => {
var listEmployee = [];
var listInvoice = [];
const employeeRef = admin.firestore().collection('employee');
const invoiceRef = admin.firestore().collection('invoice');
const promiseFacture = new Promise((resolve,reject)=>{
return factureRef.get();
})
.then(list_invoice => {
listInvoice = list_invoice.docs.map(doc => {
return doc.data();
});
})
.catch(error => {
console.log("got an error",error);
});
const promiseEmployee = new Promise((resolve,reject)=>{
return employeeRef.get();
})
.then(list_employee => {
listEmployee = list_user.docs.map(doc => {
return doc.data();
});
})
.catch(error => {
console.log("got an error",error);
});
Promise.all([promiseInvoice, promiseEmployee])
.then((values) => {
console.log(values);
return res.send('ok');
})
.catch(error => {
console.log(error);
})
});
但是它在1秒内返回了我两个空数组
有人知道该怎么做吗?谢谢
以下内容,使用destructuring assignment syntax,可以完成:
exports.generateBonus = functions.https.onRequest(async (req, res) => {
const employeesRef = admin.firestore().collection('employee');
const invoicesRef = admin.firestore().collection('invoice');
const [employeesSnapshot, invoicesSnapshot] = await Promise.all([employeesRef.get(), invoicesRef.get()]);
const listEmployees = employeesSnapshot.docs;
const listInvoices = invoicesSnapshot.docs;
//Logging
listEmployees.forEach(snap => {
console.log(snap.data());
});
listInvoices.forEach(snap => {
console.log(snap.data());
});
//...
res.status(200).send(...); //Adapt the ... to a meaningful value
});
请注意,get()
方法返回一个Promise,因此您无需将其包装在另一个Promise中。
((请注意,我已将s添加到所有collections / snapshots变量名称中。)>]