javascript - Conditionals on a chained deferred in jquery -


let chained $.deferred this.

$.each(data, function(k, v) {     promise.then(function() {         return $.post(...);     }).then(function(data) {         if(data)... // here conditions         return $.post(...);     }).then(function(data) {         if(data)... // here condition         return $.post(...);     }) });  promise.done(function() {     console.log("all done!"); }); 

am doing right? how prevent next chain execute if condition return false, , do this:

if(data){    console.log('success'); } 

can code in between .thens?

joey, whether or not doing right depends on detail of trying achieve.

if trying build 1 long .then() chain terminal .done(), each .then()'s 'done' handler either :

  • calls asynchronous process, or
  • transparently passes data on next .then() in chain

then, code should of following form :

var promise = ...;//an expression returns resolved or resolvable promise, chain started.  $.each(data, function(k, v) {     promise = promise.then(function() {//the `.then()` chain built assignment          if(data...) { return $.post(...); }         else { return data; }//transparent pass-through of `data`     }).then(function(data) {         if(data...) { return $.post(...); }         else { return data; }//transparent pass-through of `data`     }); });  promise.done(function() {     console.log("all done!"); }).fail(function(jqxhr) {     console.log("incomplete - ajax call failed"); });     

if, however, trying same each .then()'s 'done' handler either :

  • calls asynchronous process, or
  • interrupts .then() chain

then, code should of following form :

var promise = ...;//an expression returns resolved or resolvable promise, chain started.  $.each(data, function(k, v) {     promise = promise.then(function(data) {         if(data...) { return $.post(...); }         else { return $.deferred().reject(data).promise(); }//force chain interrupted     }).then(function(data) {         if(data...) { return $.post(...); }         else { return $.deferred().reject(data).promise(); }//force chain interrupted     }); });  promise.done(function() {     console.log("all done!"); }).fail(function(obj) {//note: `obj` may data object or jqxhr object depending on caused rejection.     console.log("incomplete - ajax call failed or returned data determined then() chain should interrupted"); }); 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -