How to properly break out of a promise chain?

后端 未结 3 1371
忘了有多久
忘了有多久 2020-11-22 06:12

Based on the question here: jQuery chaining and cascading then's and when's and the accepted answer, I want to break the promise chain at a point but haven\'t yet fo

3条回答
  •  感情败类
    2020-11-22 06:42

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

提交回复
热议问题