I'm new to deferred classes in JavaScript and would like to implement a function which will loop through forms and submit them one by one.
Looks like Deferred classes are the way to accomplish this.
I tried following this answer, but for some reason my implementation starts, waits 3 seconds and completes. I want it to show a different form name every 3 seconds until it's done with all the forms then complete.
What am I doing wrong? JSFIDDLE
function syncAll() {
var promises = [];
var forms = [
{'name':'form 1'},
{'name':'form 2'},
{'name':'form 3'},
{'name':'form 4'}];
$.each(forms, function (index, value) {
var def = new $.Deferred();
setTimeout(function () {
$("#output").html("Syncing: " + value.name);
def.resolve({ 'message': 'finito!' });
}, 3000);
promises.push(def);
});
return $.when.apply(undefined, promises).promise();
}
$.when(syncAll()).done(function(response){
$("#output").html(response.message);
});
/*
syncAll().done(function (response) {
$("#output").html(response.message);
}));
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">Start</div>