How to properly break out of a promise chain?

Sounds like you want to branch, not to break – you want to continue as usual to the done. A nice property of promises is that they don’t only chain, but also can be nested and unnested without restrictions. In your case, you can just put the part of the chain that you want to “break” away inside your if-statement:

Menus.getCantinas().then(function(cantinas) {
    Menus.cantinas = cantinas;

    if (cantinas.length == 0)
        return Menus; // break!

    // else
    return $.when(Menus.getMeals(cantinas), Menus.getSides(cantinas))
    .then(function(meals, sides) {
        Menus.sides = sides;
        Menus.meals = meals;
        return Menus.getAdditives(meals, sides);
    }).then(function(additives) {
        Menus.additives = additives;
        return Menus;
    });
}).done(function(Menus) {
    // with no cantinas, or with everything
});

Leave a Comment