【发布时间】:2015-06-12 12:31:16
【问题描述】:
基于这里的问题:jQuery chaining and cascading then's and when's 和接受的答案,我想在某个点打破承诺链,但还没有找到正确的方法。有multiplepostsabout这个,还是迷路了。
从原始问题中获取示例代码:
Menus.getCantinas().then(function(cantinas){ // `then` is how we chain promises
Menus.cantinas = cantinas;
// if we need to aggregate more than one promise, we `$.when`
return $.when(Menus.getMeals(cantinas), Menus.getSides(cantinas));
}).then(function(meals, sides){ // in jQuery `then` can take multiple arguments
Menus.sides = sides; // we can fill closure arguments here
Menus.meals = meals;
return Menus.getAdditives(meals, sides); // again we chain
}).then(function(additives){
Menus.additives = additives;
return Menus; // we can also return non promises and chain on them if we want
}).done(function(){ // done terminates a chain generally.
// edit HTML here
});
如果cantinas.length == 0,我将如何打破链条?我不想得到饭菜,也不想得到添加剂,坦率地说,我想称之为某种“空结果”回调。我尝试了以下非常丑陋(但有效......)。教我正确的方法。这仍然是一个有效的结果,因此本身不是“失败”,我想说的只是空结果。
var emptyResult = false;
Menus.getCantinas().then(function(cantinas){
Menus.cantinas = cantinas;
if (cantinas.length == 0) {
emptyResult = true;
return "emptyResult"; //unuglify me
}
return $.when(Menus.getMeals(cantinas), Menus.getSides(cantinas));
}).then(function(meals, sides){
if (meals == "emptyResult") return meals; //look at my ugliness...
Menus.sides = sides;
Menus.meals = meals;
return Menus.getAdditives(meals, sides);
}).then(function(additives){
if (additives == "emptyResult") return additives;
Menus.additives = additives;
return Menus;
}).done(function(){
if (emptyResult)
//do empty result stuff
else
// normal stuff
});
【问题讨论】:
标签: jquery promise break chain