【问题标题】:Difference on Mongoose using Promise or Async/Await?Mongoose 使用 Promise 或 Async/Await 的区别?
【发布时间】:2019-04-17 18:50:48
【问题描述】:

使用 ExpressJs(作为 Node.js 的 Web 框架)和 Mongoose(用于建模 MongoDB)来创建 Web 服务。我有一个关于从某些 mongoose 方法(保存、查找、findByIdAndDelete 等)处理返回对象的最佳方法的问题。

正如猫鼬文档所说,Model.prototype.save() 将返回 «Promise,undefined» 如果与回调一起使用则返回 undefined,否则返回 Promise。 更多信息:https://mongoosejs.com/docs/api.html#model_Model-save

所以我想知道我们应该使用哪一个,或者在哪种情况下一个比另一个更好?

作为使用 ES7 Async/Await 的示例:

const mongoose = require('mongoose');
const Person = mongoose.model('person');

module.exports.savePerson = async (req,res) => {
  await new Person( {...req.body} )
    .save( (err, doc)=> {
      err ? res.status(400).json(err) : res.send(doc);
    });
}

作为使用 ES6 Promise 的示例:

const mongoose = require('mongoose');
const Person = mongoose.model('person');

module.exports.savePerson = (req,res) => {
  const person = new Person( {...req.body} )

  person.save()
    .then(person => {
      res.send(person);
    })
    .catch(err => {
      res.status(400).json(err)
    });
}

【问题讨论】:

  • 这不是 promise vs async/await,因为 async/await 是 promise 的语法糖。这是 Mongoose 承诺与回调 API。回调 API 已过时。它当然不应该像上面的例子那样与 async/await 一起使用

标签: javascript node.js mongodb express mongoose


【解决方案1】:

如果你想await它,请不要使用回调:

 module.exports.savePerson = async (req,res) => {
   try {
     const doc = await new Person( {...req.body} ).save();
     res.send(doc);
   } catch(error) {
     res.status(400).json(err);
   }
};

所以我想知道我们应该使用 [.thens] 还是 [awaits] ?

这是基于意见的,但在我看来,await 更具可读性,尤其是当您必须等待多件事情时。


安全建议:不经验证直接将客户端数据传递给数据库有点危险。

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 2019-09-25
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2021-09-20
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多