I have three functions i'm trying to run, the first two are doing some async stuff that need data for the third to use. I want the third function to fire only when 1 and 2 are both done. this is the general structure but the final function is firing before 1 and 2 finish.
function run() {
var data1 = {};
var data2 = {};
$.when(first(), second()).done(constructData());
function first() {
var d = new $.Deferred();
//do a bunch of stuff async
data1 = {};
d.resolve();
}
function second() {
var d = new $.Deferred();
//do a bunch of stuff async
data2 = {};
d.resolve();
}
function constructData() {
//do stuff with data1 and data2
}
}
Answer was to not call construct data immediately
$.when(first(), second()).done(constructData);
You should return promise object. You also have an error in this line:
it should be
So all together it could be:
http://jsfiddle.net/FwXZC/
I think you should have
first()
andsecond()
return a promise:return d.promise();
. From the docs:I suspect this might be why the
when
call is callingconstructData
too soon.It's hard to tell from you code, but be sure you are calling
d.resolve()
after the async operations have completed.You might find that a more natural approach to explicitly setting
data1
anddata2
is instead to use the data that is supplied whenresolve
is called. This would mean that yourwhen
call would look something like this:Note that the exact format of results supplied to the
done
method depends on the nature of the deferred objects. If the promises are returned from a call to$.ajax
, the results should be of the form[data, statusText, jqXhrObject]
.