我不确定我是否能从经典的猫鼬回调和ES6承诺中获得好处和好处。 这个聚合查询
router.get('/', function(req,res) {
caseNote.aggregate([
{$unwind: '$field'},
{$match: {field: "aaa"}},
{$project: {field: 1, _id: 0}}
])
.exec(function(err, data) {
if (err)
res.json(err);
else {
if(data[0])
res.json(data[0].field);
else
res.json([]);
}
});
});
某些ES6糖会被转入
router.get('/', cache, function(req,res) {
caseNote.aggregate([
{$unwind: '$field'},
{$match: {field: "aaa"}},
{$project: {field: 1, _id: 0}}
])
.exec()
.then(data => res.json(data[0] ? data[0].field: {error:"result error"}))
.catch(err => res.json(err) );
});
为什么我更喜欢then() & catch()
兄弟而不是exec()
回调?
答案 0 :(得分:0)
使用ES6承诺,代码变得更清晰,更易读,因为您可以利用catch()
方法并在一个代码块中处理错误。
在这个具体的例子中,我没有看到太大的区别,因为没有多个回调。
这篇文章非常详细。
https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch3.md