【发布时间】:2021-08-28 16:52:11
【问题描述】:
下午好, 我正在使用 MERN 堆栈制作一个简单的发票应用程序。 我有一个运行 2 forEach() 的函数,它通过数据库和用户中的发票。如果电子邮件匹配,则它会为该用户提供发票。 当我将 DBElement 记录到控制台时,它可以工作,它有正确的数据,但是当我将 test1 记录到控制台(app.get())时,它只有一个对象,而不是两者。
// forEach() function
function matchUserAndInvoice(dbInvoices, dbUsers) {
dbInvoices.forEach((DBElement) => {
dbUsers.forEach((userElement) => {
if(DBElement.customer_email === userElement.email){
const arrayNew = [DBElement];
arrayNew.push(DBElement);
app.set('test', arrayNew);
}
})
})
}
// end point that triggers the function and uses the data.
app.get('/test', async (req,res) => {
const invoices = app.get('Invoices');
const users = await fetchUsersFromDB().catch((e) => {console.log(e)});
matchUserAndInvoice(invoices,users,res);
const test1 = await app.get('test');
console.log(test1);
res.json(test1);
})
【问题讨论】:
-
还要注意
matchUserAndInvoice()是异步的,你不会等待它完成,所以即使其余代码是正确的(它不是),那么你的console.log(test1)不会显示上一次调用matchUserAndInvoice()的结果,因为它还没有完成它的工作。
标签: javascript node.js reactjs express for-loop