In the example below I have a function that calls another function (which in reality may call a further function or make an Ajax request).
The example works for deferring the first function but I have no idea how to make it resolve other functions that it may call.
Do I have to pass these deferred objects around to the other functions, or is there a more elegant way around this? (In reality, I'm dealing with speech synthesis using the API callbacks so the basic structure in the example can't be changed so much).
Fiddle here https://jsfiddle.net/macgroover/ahz46rw1/
function slowCount(numbers, deferred) {
if (deferred) {
this.deferred = jQuery.Deferred();
}
if (numbers.length) {
var number = numbers.shift();
log('SC:' + number);
setTimeout(function() {
doSomething(number);
slowCount(numbers);
}, 500);
return this.deferred.promise();
} else {
this.deferred.resolveWith(this, ['resolveWith']);
//this.deferred.resolve();
return;
}
}
function doSomething(number) {
setTimeout(function() {
log("DS:" + number);
}, 1000);
}
$(function() {
$.when(slowCount([1, 2, 3, 4], true)).done(function(rslt) {
log("All tasks finished with " + rslt);
});
});