Synchronization with when.js
This test synchronizes 100 asynchronous callbacks using when.js promise implementation.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
CSS
h1 { font-size: 5em; font-weight: bold; }
JavaScript
console.clear();
function doAlotOfAsyncThings(callback) {
var promises = [];
var def = $.Deferred();
console.log('Adding first promise');
promises.push(def.promise());
setTimeout(function() {
// Dinamically adding second promise. Important note: last added promise must be added to array BEFORE previous promise has been resolved
var def2 = $.Deferred();
var def3 = $.Deferred();
console.log('Dinamically adding second and third promises');
promises.push(def2.promise());
promises.push(def3.promise());
console.log('Resolving first promise');
def.resolve();
setTimeout(function() {
console.log('Resolving second and third promises');
def2.resolve();
def3.resolve();
}, 1500);
}, 1000);
function checkAllDone() {
console.log('Checking $.when');
$.when.apply(null, promises).then(function() {
var all_resolved = _.every(promises, function(elem) { return elem.state() == 'resolved'; });
if(all_resolved) {
console.log('All promises are resolved! callback();')
callback();
} else {
console.log('Hm, seems that some promises were dinamically added, waiting for them..');
checkAllDone();
}
})
}
checkAllDone();
}
doAlotOfAsyncThings(function(){
console.log('Done')
});