如何确保在Node JS上的render()之前执行查询

时间:2018-09-17 06:06:28

标签: javascript node.js express asynchronous mongoose

我不知道这是否是异步问题,因此有时结果没有产品数据,而只有类型数据。但是,有时它将同时具有这两个数据。

我的设置: Node JS,Express,猫鼬

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()函数。

谢谢!

1 个答案:

答案 0 :(得分:3)

由于两个异步操作都返回(83952, 192) ,因此您应该使用Promise,这两个操作都将完成。不需要外部Promise.all对象,只需直接使用已解析的Promise的值即可。另外,使用Promises时,请不要忘记使用data处理错误:

catch