【问题标题】:How to break promise chain in Mongoose如何在猫鼬中打破承诺链
【发布时间】:2014-08-05 02:01:07
【问题描述】:

我正在迁移我的 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);
});

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

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

Mongoose Docs,你会想要调用promise的#reject方法。

reject 的处理程序应检查原因并“做正确的事”(例如,如果您正在执行 RESTful 操作,则返回 404 或空数组)

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

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

【讨论】:

  • 好的,但是如何调用拒绝方法?
猜你喜欢
  • 2019-06-04
  • 2017-11-23
  • 2018-02-15
  • 2020-02-23
  • 2016-11-01
  • 2015-05-12
  • 2018-09-01
  • 1970-01-01
相关资源
最近更新 更多