【问题标题】:How to make sure the query executed before render() on Node JS如何确保在 Node JS 上的 render() 之前执行查询
【发布时间】:2019-02-21 00:24:20
【问题描述】:

不知道是不是异步问题,所以有时候结果没有产品数据,只有类型数据。但是,有时它会有两个数据。

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

谢谢!

【问题讨论】:

    标签: javascript node.js express asynchronous mongoose


    【解决方案1】:

    因为两个异步操作都返回Promises,所以您应该使用Promise.all,这将在两者都完成时解决。不需要外部的 data 对象,只需直接使用已解析承诺的值即可。另外,在使用 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
        });
    });
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2015-05-30
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2020-12-21
    • 1970-01-01
    相关资源
    最近更新 更多