jQuery Deferred not working like expected -
i work jquery , deferred , there (for me) unexpected behavior. hope can explain me.
what plan is: want iterate on list of keys. every key create deferred , call function (dosomething), pass key , callback method (where resolve deferred). after call add deferred list. function dosomething async , calls @ end overgiven callback method. after iteration, await deferreds , display alerts.
the following snippet first try, isn't working correct. expected 3 alerts '0', '1' , 'first,second'. '1'.
var dosomething = function(key, callback) { window.settimeout(function() { callback(key); }, 0) } var items = new array(); var processes = new array(); var keys = ['first', 'second']; (var idx in keys) { var deferred = $.deferred(); dosomething(keys[idx], function(item) { items.push(item); deferred.resolve(); }); processes.push(deferred.promise()); } processes[0].done(function() { alert('0'); }) processes[1].done(function() { alert('1'); }) $.when.apply($, processes).done(function() { alert(items); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
the second try without async call in dosomething , 3 alerts.
var dosomething = function(key, callback) { callback(key); } var items = new array(); var processes = new array(); var keys = ['first', 'second']; (var idx in keys) { var deferred = $.deferred(); dosomething(keys[idx], function(item) { items.push(item); deferred.resolve(); }); processes.push(deferred.promise()); } processes[0].done(function() { alert('0'); }) processes[1].done(function() { alert('1'); }) $.when.apply($, processes).done(function() { alert(items); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
the last try async call in dosomething , work in 'seperate' function called func. gets me expected 3 alerts.
var dosomething = function(key, callback) { window.settimeout(function() { callback(key); }, 0) } var items = new array(); var processes = new array(); var keys = ['first', 'second']; var func = function(key) { var deferred = $.deferred(); dosomething(key, function(item) { items.push(item); deferred.resolve(); }); return deferred.promise(); } (var idx in keys) { processes.push(func(keys[idx])); } processes[0].done(function() { alert('0'); }) processes[1].done(function() { alert('1'); }) $.when.apply($, processes).done(function() { alert(items); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
so question is: why first try not working expected? can't explain why.