如何使用 Q 和 JS 捕获或失败来处理错误

How to handle errors using Q and JS catch or fail

本文关键字:失败 处理 错误 何使用 JS      更新时间:2023-09-26

我的代码:

Question.find({
    _id : req.headers['questionid']
}, {
    question : 1,
    tags : 1
}, function(req, foundQ) {
    // doSome stuff with foundQ
}).then(function(foundQ) {
    //some more action
});
<小时 />

我的问题 :

如果 mongoDB 查找调用无法从 id 中找到问题,我不希望调用.then部分。我希望最后都跳到失败块。

我试过添加 .fail(function() { });和最后.catch(function() { });,但这似乎不起作用。

我特别需要做什么?为什么失败/捕获不起作用?

否则。我正在使用 Q - 里面有什么东西可以使用吗?

谢谢。

你可以做这样的事情:

Question.find({
    _id : req.headers['questionid']
}, {
    question : 1,
    tags : 1
}, function(req, foundQ) {
    if(!foundQ){
         return q.reject("I don't found anything");
    }
    // doSome stuff with foundQ
}).then(function(foundQ) {
    //some more action
});

mongo 节点驱动程序的事件当查询返回空时不要抛出错误,如果结果未定义,您可以在下一个"then"中"模拟"错误。