gpt4 book ai didi

javascript - Node.js - 在返回响应之前不运行数据库 promise

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:56 27 4
gpt4 key购买 nike

我的 Node 服务器上有这个请求处理程序。它有三个 MongoDB 查询,我希望在发送响应之前返回所有结果。

api.get('/getStats/:productID', (req,res)=>{
let data = {};
let dailySales = [];
let avgProduct = "";
let customers = [];

Sales.find({productID: productID}).then(
sales => {
dailySales = sales;
}
);

Products.find({}).then(
products => {
// Calculate Avg product here
avgProduct = result;
}
);

Customers.find({}).then(
customers => {
customers = customers;
}
);

data = {
dailySales,
avgProduct,
customers
};

res.json(data);
});

但是运行这个会返回

data: {
dailySales: [],
avgProduct: "",
customers: []
}

即Mongo 响应在数据运行之前返回。请问我该如何解决。谢谢您

最佳答案

在发送实际响应之前等待所有 promise 解决

const sales = Sales.find({productID: productID});
const allProducts = Products.find({});
const allCustomers = Customers.find({});

Promise.all([sales, allProducts, allCustomers])
.then(data => res.json(data));

关于javascript - Node.js - 在返回响应之前不运行数据库 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53449067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com