如果我有一个检查是否存在特定ID的调用 - 如果在开始时发现错误,我如何退出整个事件。
我知道我可以用if-else块来做,但是有一个'更容易阅读'的1行方式。
e.g:
Question.find({_id: req.headers['questionid']}, {question:1, tags:1},
function(err, foundQ) {
if(!err) {
//skip everything below including the then
}
})
.then(function(foundQ){
//Some more stuff here
})
另外,fyi - 我在另一段代码中使用了Q框架 - 所以如果有其他方法可以指导我也可以提供帮助。
答案 0 :(得分:1)
如果你想要突破一个函数,与.then
链接而不调用以下.then
,你可以抛出一个错误throw new Error('this is an error');
。但是使用mongoose和promises,您应该能够使用这种方式而只是.find().exec().then().catch();
,并且您的错误最终应该在.catch
中。无需在find
中进行回调。
Question.find({_id: req.headers['questionid']}, {question:1, tags:1}).exec().
.then(function(foundQ){
//Some more stuff here
})
.catch(function(err){
})
答案 1 :(得分:0)
根据mongoose docs;
find
方法返回Query对象。
exec
方法返回一个承诺。
所以Question.find().exec().then()
用法应该按预期工作。
参考文献;