提问者:小点点

Mongoose使用Promise还是Async/Await的区别?


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

正如mongoose文档所说,model.prototype.save()将返回“Promise.undefined”,如果与回调一起使用,则返回未定义,否则返回一个Promise。有关更多信息:https://mongoosejs.com/docs/api.htmlUpmodel_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承诺示例:

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)
    });
}

共1个答案

匿名用户

如果要它,则不要使用回调:

 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]还是[waits]?

这是基于观点的,但在我看来更易读,尤其是当您必须等待多个东西时。

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