【问题标题】:Synchronous and asynchronous vs callback in mongoose猫鼬中的同步和异步与回调
【发布时间】:2019-10-12 15:05:05
【问题描述】:

大家好,我是节点新手,有一个简单的问题,这两个狙击有什么区别

注意:我知道 async / await 功能,并且在前端应用程序中,处理异步操作是最佳实践,但在使用 mongoose 的节点中,我想知道哪种方法更适合处理

第一个解决方案

// for example we pass this function as controller to route handler

exports.myController = async (req, res, next) => {

try {
     const data = await Model.find();
     const some = await new Model(data).save();
   } catch(e) {

    next(e);
 }
}

第二种解决方案

exports.myController = (req, res, next) => {

 const data = Model.find((err, data_) => {

  const some = new Model(data_);
  some.save((err, result) => {
  ....
})

});

}


我想知道我什么时候有来自 mongoose 的错误,第二种方式可以抛出这样的错误

// in callback function 

if (err) {

throw Error();

}

但是我如何在async/await 解决方案中处理这个问题

【问题讨论】:

    标签: javascript node.js mongodb asynchronous mongoose


    【解决方案1】:

    您只需将其扔掉或将其记录到您的 catch 块中:

    try {
         const data = await Model.find();
         const some = await new Model(data).save();
       } catch(e) {
         throw e; 
         next(e);
     }
    

    async/await 像 Promise 一样工作,但没有嵌套回调,它会抛出一个与首先发生的错误同步的错误,并停止执行其他行。

    基于您编辑的注释:
    您应该始终在 nodejs 中使用异步解决方案方式,甚至对于与 javascript 相关的任何事情,它都是最好的可组合和可重用的解决方案。

    【讨论】:

      猜你喜欢
      • 2016-04-03
      • 2021-12-04
      • 2015-10-23
      • 1970-01-01
      • 2014-11-16
      • 2018-08-30
      • 2018-03-09
      • 2023-04-08
      • 2014-11-19
      相关资源
      最近更新 更多