首页 > 解决方案 > 如何确保在 Node JS 上的 render() 之前执行查询

问题描述

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

我的设置: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() 函数。

谢谢!

标签: javascriptnode.jsexpressasynchronousmongoose

解决方案


因为两个异步操作都返回Promises,所以您应该使用Promise.all,这将在两者都完成时解析。不需要外部data对象,只需直接使用已解析承诺的值即可。另外,不要忘记catch在使用 Promises 时处理错误:

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
    });
});

推荐阅读