1

I've a bug, and I suspect is due to my bad knowledge of jQuery. The scenario is described in the snipped below:

var towait = [];

towait.push($.get('someurl',function(data){ dosomething...}));
towait.push($.get('someurl',function(data){ dosomething...}));
....
towait.push($.get('someurl',function(data){ dosomething...}));

$.when(towait).done(function(){ dosomething else});

Symptoms are that dosomething else is executed before the dosomething calls ( maybe I'm wrong, I'm hunting a bug ) is my assumption correct? does the defferred appear to be joined in the when before the $.get(...,function(){}) is executed? If so there is some way in changing this behavior?

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
  • if one request is rejected, $.when callback is fired. There is a nice subject about $.deferred objects here: http://stackoverflow.com/questions/16780286/jquery-ajax-deferred-callback-orders/16780565#comment24179307_16780565 if that can help?! – A. Wolff Jun 06 '13 at 08:53
  • @roasted tracing with the debugger I see 'do something else'called before dosomething. Some items in the array are undefined, but hte undefined should be treated as resolved objects. – Felice Pollano Jun 06 '13 at 09:07
  • This would be an example of a multiple-deferred case. According to the [doc](http://api.jquery.com/jQuery.when/), `In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point.` – Dom Jun 06 '13 at 09:29
  • possible duplicate of [jQuery $.when() with variable arguments](http://stackoverflow.com/questions/8011652/jquery-when-with-variable-arguments) – Felix Kling Jun 09 '13 at 12:31

1 Answers1

3

In the doc of when() method, i see as only parameter deferred objects. Here you pass an array which is not an deffered object. You want to pass each request as parameter.

Try this:

$.when.apply($,towait).done(function(){ dosomething else});

DEMO

Of course, if one request is rejected, the $.when callback is fired before any other request are done.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • you are correct indeed: I was convinced passing an array of deferred object would be the same as passing many deferred objects. This is basically due to the fact than jQuery usually do things as we imagine soo well :) – Felice Pollano Jun 06 '13 at 09:38
  • Ya, this is in fact the same as it: http://jsfiddle.net/tJE65/1/ $.when(one,two,three).done(function(){ console.log('DONE')}); like you already know i suppose – A. Wolff Jun 06 '13 at 09:44