05.28 在express+mongoose項目中使用ES7的async和await

內容導讀

不知道我是不是最後一個知道的,反正現在在工程中用的超級爽!不需要bluebird,不需要co,把Promise 的then轉化為同步代碼簡直high翻天。是不是很蛋疼?我竟然這樣寫完了幾乎整個工程。首先是方法名上加async,再就是每個mongoose操作上加await,就變成了同步方法。其次是,不要再每個操作捕捉錯誤,類似 (err=>{next(err)}) 。

不知道我是不是最後一個知道的,反正現在在工程中用的超級爽!

不需要bluebird,不需要co,把Promise 的then轉化為同步代碼簡直high翻天。。。

要求:

mongoose v>4
node v>8

比如這樣一個需求:在添加班級時,同步更新學校中的refs,如果用then來寫:

 create(req, res, next) {
// 本學校下不允許創建重複專業
const major = req.body.major;
MajorSchema.findOne({
name: major.name,
school: major.school
}).then(r => {
if (r) {
//constructor(message, status = httpStatus.INTERNAL_SERVER_ERROR, isPublic = false)
return next(
new APIError(
'本學校下已有相同名稱專業',
httpStatus.INTERNAL_SERVER_ERROR,
true
)
);
}
const item = new MajorSchema(major);
item._id = mongoose.Types.ObjectId();
item
.save()
.then(saved => {
//更新school中的引用
SchoolSchema.findById(major.school).then(school => {
if (school) {
if (!school.majors.includes(saved._id)) {

school.majors.push(saved._id)
SchoolSchema.findByIdAndUpdate(major.school, {
majors: school.majors
}).then(savedSchools => {
res.json(saved);
})
}
}
})
})
.catch(e => next(e));
});
}

是不是很蛋疼?我竟然這樣寫完了幾乎整個工程。。。

昨天發現了async,就象發現了新大陸,使用async-await,寫這樣的需求:移除專業時,同步移除學校中的refs:

 async remove(req, res, next) {
try {
const major = await MajorSchema.findByIdAndRemove(req.params.id).exec()
//刪除學校中的ref
if (major) {
const school = await SchoolSchema.findById(major.school).exec()
if (school && school.majors.includes(major)) {
school.majors.splice(school.majors.findIndex(s => s === major._id), 1)
const updatedSchool = await SchoolSchema.findByIdAndUpdate(school._id, {
majors: school.majors
}).exec()
res.sendStatus(httpStatus.OK)
}
}
} catch (err) {
next(err)
}
}

首先是方法名上加async,再就是每個mongoose操作上加await,就變成了同步方法。

其次是,不要再每個操作捕捉錯誤,類似(err=>{next(err)})。這個寫 唉

注意一下並不是所有mongoose操作都支持await,只有返回promise的才可以,具體可以看mongoose官網文檔:http://mongoosejs.com/docs/


分享到:


相關文章: