1

In my code below, if any defer fails it goes to fail block and everything is lost. What I want here is , to ignore failed ones and grab successful ones. Any graceful way to do it? and How would I go to failed block if all defers fail. One work around could be to take a for loop and process deferredItems array in that loop one by one, but that is not graceful way to do it.

$.when.apply($, deferredItems).done(function(){

}).fail(function(errorObj) {

});
Ahmad
  • 2,110
  • 5
  • 26
  • 36
  • 1
    There's nothing built in to jQuery, if one deferred fails, the `$.when` does as well, that's the way it's designed – adeneo Jan 22 '16 at 14:40

2 Answers2

1

Use .always()

$.map([a, b], function(d) {
  $.when(d).always(function(data) {
    console.log(data)
  })
})
guest271314
  • 1
  • 15
  • 104
  • 177
1

You can use .always, and then find the ones which were resolved, as you suggested

$.when.apply($, deferredItems).always(function(){
  var resolvedDeferreds = $.grep(deferredItems, function(deferred){
    return deferred.state() === 'resolved';
  });

  //do stuff with resolved deferreds
})

Edit:

It turns out this isn't going to work. The .always callback gets called immediately once one deferred fails and doesn't wait for the remaining pending deferreds. It looks like there's no way to wait for an array of defereds to all get either resolved or rejected using just jquery.when as is.

yts
  • 1,890
  • 1
  • 14
  • 24
  • and if all defers fail, I need to go to fail block, is there anyway I can switchover to fail block if I dont get any resolved.? – Ahmad Jan 22 '16 at 15:13