Using synchronous function within jQuery when/then
by riddla
HTML
<ol></ol>
JavaScript
$ol = $('ol');
function appendLi(str, color) {
$ol.append('<li style="color:' + color + '">' + str + '</li>');
}
function syncModule() {
appendLi('I synchronously', 'green');
appendLi('do', 'green');
appendLi('things', 'green');
}
function asyncModule(color) {
if (typeof color === 'undefined') {
color = 'blue';
}
appendLi('I asynchronously', color);
appendLi('do', color);
return $.Deferred(function(dfd) {
setTimeout(function() {
appendLi('things', color);
dfd.resolve();
}, 2000);
});
}
$.when(asyncModule('firebrick'))
.then(syncModule)
.then(asyncModule);