I'm trying to get some data in multiple functions and would like to chain them in order to execute the last function only when all data was properly loaded.
The problem is that the functions in the .done() part will be called instantly and don't wait until the Deferred-Object is resolved. I also tried it by chaining them with .then() but this also didn't work.
var array1, array2;
function doStuffWithReceivedData() {
// Working with the data
}
function getArray1() {
var defArray1 = $.Deferred();
$.getJSON(url, function(data) {
if (data.success) {
array1 = data.payload;
defArray1.resolve();
} else {
// Information displayed that there was an error
}
})
return defArray1;
}
// Function 2 is like the first one
function getArray2() {...};
$(document).read(function() {
getArray1()
.done(getArray2()
.done(doStuffWithReceivedData()));
}
The argument to .done()
must be a function. You're calling the function, not passing it. Take off the parentheses.
$(document).ready(function() {
getArray1()
.done(function() {
getArray2().done(doStuffWithReceivedData));
}
}