不知道是不是异步的问题,导致有时候结果没有产品数据,只有类型数据。然而,有时它会同时拥有这两种数据。
我的设置: Node JS、Express、 Mongoose
router.get('/', function (req, res, next) {
var data = {};
Product.find().limit(4).populate({path: 'region_id', model: Region})
.then(function (doc) {
data.product = doc;
});
Type.find()
.then(function (doc) {
data.type = doc;
});
res.render('index', {title: 'Home', items: data});
});
如果我是正确的,那么如何确保在运行 render() 之前执行所有 find() 函数。
谢谢!
最佳答案
因为两个异步操作都返回 Promise
,所以您应该使用 Promise.all
,这将在两者完成时解析。不需要外部 data
对象,只需直接使用已解析的 promise 的值。另外,不要忘记在使用 Promises 时使用 catch
处理错误:
router.get('/', function (req, res, next) {
Promise.all([
Product.find().limit(4).populate({path: 'region_id', model: Region}),
Type.find()
])
.then(([product, type]) => {
res.render('index', {title: 'Home', items: { product, type } });
});
.catch((err) => {
// handle errors
});
});
关于javascript - 如何确保在 Node JS 上的 render() 之前执行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52361618/