2

I'm migrating my Mongoose code to use Promises to avoid The Pyramid of Doom. I want to break the Promise's chain on a certain point, but I don't know how to do it. Here's my code:

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);
});
fonini
  • 3,243
  • 5
  • 30
  • 53
  • Break, as in stop it from running because there's an error condition? – tkone Aug 04 '14 at 12:26
  • Yeah, if there's no result on the first query, I don't want to proceed to the next query. – fonini Aug 04 '14 at 12:27
  • See https://stackoverflow.com/questions/28803287/how-to-break-promise-chain/45339587#45339587 Use `return { then: function() {} };` – Martin Jul 27 '17 at 00:50

1 Answers1

3

You need to reject or throw an error in the handler to "stop" a promise chain from running.

From the Mongoose Docs, you would want to call the #reject method of the promise.

The handler you have for reject should examine the reason and "do the right thing" (like cause a 404 to be returned or an empty array if you're doing RESTful stuff)

If you don't have access to the promise (since you're in the handler already for example), just throw new Error().

This will invoke the rejected handler you provided.

tkone
  • 22,092
  • 5
  • 54
  • 78