fonini
fonini

Reputation: 3341

How to break promise chain in Mongoose

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

Upvotes: 2

Views: 2140

Answers (1)

tkone
tkone

Reputation: 22728

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.

Upvotes: 3

Related Questions