如何打破猫鼬的承诺链

时间:2014-08-04 12:19:28

标签: node.js mongodb mongoose

我正在迁移我的Mongoose代码以使用Promises来避免毁灭金字塔。 我想在某一点打破Promise的链条,但我不知道该怎么做。 这是我的代码:

var data = {};

People.find({}).exec()
.then(function(people) {

    if (people.length == 0){
        // I want to break the chain here, but the console.log() gets executed
        res.send('No people');
        return;
    }

    data['people'] = people;

    return Events.find({
        'city': new mongoose.Types.ObjectId(cityID)
    }).lean().exec();

}).then(function(events) {
    console.log('here');
    data['events'] = events;

    res.send(data);
});

1 个答案:

答案 0 :(得分:3)

您需要在处理程序中拒绝或抛出错误,以“停止”承诺链的运行。

Mongoose Docs开始,您需要调用承诺的#reject方法。

你对reject的处理程序应该检查原因并“做正确的事情”(如果你正在做RESTful的东西,就会导致返回404或空数组)

如果您无法访问承诺(例如,因为您已经在处理程序中),只需throw new Error()

这将调用您提供的被拒绝的处理程序。