Mongoose / JS – 跳出代码,跳过任何块

如果我有一个电话来检查是否存在一个特定的ID – 如果在开始时发现错误,我该如何退出整个事情。

我知道我可以做一个if-else块,但是有一个“更容易阅读”1行的方式。

例如:

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 }) 

另外,我在另一段代码中使用了Q框架 – 所以如果有另一种方法,那么有人可以指导我也可以提供帮助。

如果你想打破一个函数,链接.then而不是调用以下。你可以抛出一个错误throw new Error('this is an error'); 。 但是对于mongoose和承诺,你应该能够使用这种方式,而只需要执行.find().exec().then().catch(); ,你的错误应该以.catch 。 找不到需要的callback。

 Question.find({_id: req.headers['questionid']}, {question:1, tags:1}).exec(). .then(function(foundQ){ //Some more stuff here }) .catch(function(err){ }) 

根据mongoose的文件;

find方法返回Query对象。

exec方法返回一个promise。

所以Question.find().exec().then()使用应该如你所料。


参考;

http://mongoosejs.com/docs/api.html#query_Query-find

http://mongoosejs.com/docs/api.html#query_Query-exec