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

标签 javascript node.js express asynchronous mongoose

不知道是不是异步的问题,导致有时候结果没有产品数据,只有类型数据。然而,有时它会同时拥有这两种数据。

我的设置: 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/

相关文章:

Javascript 使用变量继承构造函数

javascript - 在 Fabric.js 中用鼠标旋转东西的正确方法

node.js - Firebase CLI - "Invalid project ID specified"

node.js - 如何在 node.js 中将文件定义为模块

javascript - Jquery DatePicker 设置为不自动打开

javascript - 优化 Jquery 动画

node.js - 捕获 imagemagick 错误 - Node 崩溃

javascript - express 和 Mongoose : Cannot read property 'name' of undefined in Postman

node.js - Express.js sendFile 返回 ECONNABORTED

javascript - 创建新子级时如何将parent_id的外键分配给post路由