发现这段代码不是那么直截了当,并且想知道是否有人可以帮助我清理方法正在做什么。
// return an article's comments
router.get('/:article/comments', auth.optional, function(req, res, next){
Promise.resolve(req.payload ? User.findById(req.payload.id) : null).then(function(user){
return req.article.populate({
path: 'comments',
populate: {
path: 'author'
},
options: {
sort: {
createdAt: 'desc'
}
}
}).execPopulate().then(function(article) {
return res.json({comments: req.article.comments.map(function(comment){
return comment.toJSONFor(user);
})});
});
}).catch(next);
});
从我最初阅读的方法开始:
当我们在底部执行execPopulate时,我很困惑为什么我们需要在第一个populate上设置路径
答案 0 :(得分:1)
我已清理嵌套的promises以使用async-await
使其更加同步。你正走在正确的道路上,但我认为这会有很大的帮助:
async function handleRoute(req, res, next) {
try {
const id = req.payload ? req.payload.id : null
const user = await User.findById(id).exec()
if (!user) {
throw new Error('User does not exist')
}
const populateOptions = {
path: 'comments',
populate: {
path: 'author'
},
options: {
sort: {
createdAt: 'desc'
}
}
}
const article = await req.article.populate(populateOptions).execPopulate()
const comments = article.comments.map(comment => comment.toJSONFor(user))
res.json({ comments })
} catch (error) {
next(error)
}
}
router.get('/:article/comments', auth.optional, handleRoute)