[英]Difference on Mongoose using Promise or Async/Await?
使用ExpressJs(作為Node.js的Web框架)和Mongoose(用於對MongoDB建模)來創建Web服務。 我有一個關於最好的方法來處理貓鼬方法(保存,查找,findByIdAndDelete等)中的返回對象的問題。
正如貓鼬的文檔所述,Model.prototype.save()將返回«Promise,undefined»(如果未與回調一起使用,則返回undefined),否則將與Promise一起使用。 有關更多信息: https : //mongoosejs.com/docs/api.html#model_Model-save
所以我想知道我們應該使用哪一種,或者哪種情況比另一種更好?
作為使用ES7異步/等待的示例:
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)
});
}
如果要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
的方式更具可讀性,尤其是當您必須等待多種情況時。
安全建議:未經驗證直接將客戶端數據傳遞到數據庫有點危險。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.