jquery - Waiting for multiple deferred objects to be finished and use the resolved values -
i trying figure out way wait multiple deferred objects , process them once done, may start next set deferred objects.
i stuck because result of following not expected be. expecting result
alldone resovled values 1,2,3
the actual result is
alldone resovled values 1,2
var dfd1 = new $.deferred(); var dfd2 = new $.deferred(); var dfd3 = new $.deferred(); var dfds = [ dfd1, dfd2, dfd3 ]; var resolvedvalues = []; $.when.apply($, dfds).done(function() { dfds.foreach(function(dfd){ console.log("inloop"); dfd.promise().done(function(value) { resolvedvalues.push(value); }); }); console.log("alldone resovled values are" + resolvedvalues); }) dfd1.resolve(1); dfd2.resolve(2); dfd3.resolve(3);
for why, see below. you're overcomplicating it. :-) callback give final promise when
gives resolved values arguments:
$.when.apply($, dfds).done(function(a, b, c) { // here, 1, b 2, c 3 // or can access them on `arguments` })
live example:
var dfd1 = new $.deferred(); var dfd2 = new $.deferred(); var dfd3 = new $.deferred(); var dfds = [ dfd1, dfd2, dfd3 ]; var resolvedvalues = []; $.when.apply($, dfds).done(function() { // use trick turn `arguments` real array var = array.prototype.slice.call(arguments); // show got snippet.log("alldone: " + a.join(", ")); }) dfd1.resolve(1); dfd2.resolve(2); dfd3.resolve(3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- script provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
side note: assume you're dealing array on purpose. if have fixed number of promises need wait on, use simpler form
$.when(dfd1, dfd2, dfd3).then(function(a, b, c) { // ... });
here's why you're getting odd result you're getting: jquery's deferred
/promise
objects have problem in chaotic: when call done
on them, don't know whether callback executed synchronously or asynchronously. serious flaw, , 1 true promises/a+ implementation not have (the callback asynchronous).
jquery call callback asynchronously if promise not yet resolved. call synchronously if isn't resolved:
var d1 = $.deferred(); d1.done(function() { console.log("i'm called asynchronously"); }); d1.resolve(); var d2 = $.deferred(); d2.resolve(); d2.done(function() { console.log("i'm called synchronously"); });
so what's happening in code overall done
callback when
fires fired during done
callback on last promise got resolved (dfd3
). since promise isn't marked resolved until after done
callbacks have been completed, when code runs, dfd1
, dfd2
resolved dfd3
still in process of being resolved. inner callbacks called synchronously dfd1
, dfd2
asynchronously dfd3
. you're outputting result before dfd3
return value has been pushed onto array.
Comments
Post a Comment