我对 Node 很陌生.js并且由于嵌套回调而感到沮丧,这使得阅读代码和排除拼写错误非常困难。
正如您在下面看到的,我有 2 个关联的模型(博客和评论(和 app.get 方法,我为博客文章创建评论。
Model Structure:
Blog
..title (string)
..blog (string)
..comments (Referenced Comment Model)
....comment (string)
Comment
..comment(string)
目前 app.get 方法有 3 个嵌套的回调函数,可能的错误只有 console.logging 尚未(如果我开始为错误编写更多代码,为了获得更好的用户体验,函数变得非常混乱(。
app.post('/blog/:id/comment',function(req,res){
Comment.create(req.body.comment, function(err, newComment){
if (err) {
console.log(err);
} else {
Blog.findById(req.params.id, function(err, foundBlog){
if (err){
console.log(err);
} else {
foundBlog.comments.push(newComment);
foundBlog.save(function(err, data){
if(err){
console.log(err);
} else {
res.redirect('/blog/'+req.params.id);
}
});
}
});
}
});
});
在这里,我想征求您的建议,以简化下面的功能以及如何更好地处理错误。
正如其他人所评论的那样,承诺是要走的路,而异步/等待通常是编写承诺的最优雅的方法。例如,您的代码可以压缩为以下内容。您应该阅读承诺,因为它们是节点开发的重要概念。
app.post('/blog/:id/comment', async function(req,res){
try{
const newComment = await Comment.create(req.body.comment);
const foundBlog = await Blog.findById(req.params.id);
foundBlog.comments.push(newComment);
await foundBlog.save();
res.redirect('/blog/'+req.params.id);
}
catch(err){
console.log(err);
}
});
看起来你正在使用支持承诺的猫鼬,所以你可以做这样的事情:
app.post('/blog/:id/comment',(req,res) {
Comment.create(req.body.comment)
.then(newComment => {
return Blog.findById(req.params.id))
.then(foundBlog => {
foundBlog.comments.push(newComment)
return foundBlog.save()
})
})
.then(() => res.redirect('/blog/' + req.params.id))
.catch(err => console.log(err))
})
您也可以使用 async-await:
app.post('/blog/:id/comment', async (req, res) {
try {
const newComment = await Comment.create(req.body.comment)
const foundBlog = await Blog.findById(req.params.id)
foundBlog.comments.push(newComment)
await foundBlog.save()
res.redirect('/blog/' + req.params.id)
}
catch(err) {
console.log(err)
}
})