【问题标题】:Express JS mongoDB async awaitExpress JS mongoDB 异步等待
【发布时间】:2018-06-11 05:01:46
【问题描述】:

在猫鼬从数据库中获取数据之前,任何人都可以帮助我在哪里生成问题视图。我已经使用 await 但它不等待响应。

router.get('/', async(req, res, next)=> {
    try{
        const products = await Product.find({});
        res.render('shop/index', { title: 'Express',products });
    }catch(e){
        console.log(e);
    }

});

【问题讨论】:

  • 你是如何断定它没有等待响应的?
  • 获取所有产品信息后需要视图渲染
  • 在渲染之前尝试使用console.log记录产品

标签: node.js mongodb express asynchronous mongoose


【解决方案1】:

Imao 你试图做这样的事情:

  router.get('/', async(req, res, next)=> {
      let products
      try{
          products = await Product.find({});
      }catch(e){
          console.log(e);
      }

      res.render('shop/index', { title: 'Express',products });
  });

但据我所知,使用这种语法的原因是回调的 cristmas 树。

【讨论】:

    【解决方案2】:

    你可以这样做

    router.get('/', async(req, res, next)=> {
        try{
            Product.find({}).then(products => {
              res.render('shop/index', { title: 'Express',products });
            });
        }catch(e){
            console.log(e);
        }
    
    });
    

    【讨论】:

      猜你喜欢
      • 2019-07-20
      • 1970-01-01
      • 2013-11-13
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 2018-08-28
      • 1970-01-01
      相关资源
      最近更新 更多