Skip to content

Instantly share code, notes, and snippets.

@ruiramos
Created July 16, 2014 00:03
Show Gist options
  • Save ruiramos/6453d6b3a8f3a8f0c764 to your computer and use it in GitHub Desktop.
Save ruiramos/6453d6b3a8f3a8f0c764 to your computer and use it in GitHub Desktop.
Objective: I have 3 workers doing independent things, but I only want to update the app's state once they're all in the "same (synchronous) page" - meaning that if one updates, I want to wait for the others to update as well before showing the result. Reference implementation:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="out"></div>
</body>
</html>
// Objective: I have 3 workers doing independent things, but I only want to update the app's state once they're all in the "same (synchronous) page" - meaning that if one updates, I want to wait for the others to update as well before showing the result. Reference implementation:
var wall = function(workers){
var self = {};
self.run = function(){
// when all the promises are resolved...
$.when.apply(null, workers.map(function(el){ return el.promise; })).done(function(){
log(Array.prototype.splice.call(arguments, 0));
}).then(function(){
workers.forEach(function(w){
w.createNewPromise();
});
// cycle - wait for these new promises to reload
self.run();
});
};
return self;
};
var worker = function(name){
var self = {};
self.promise = $.Deferred();
self.load = function(){
log(name + ' loaded');
self.promise.resolve(' * Resolving for '+name);
};
self.createNewPromise = function(){
self.promise = $.Deferred();
};
return self;
};
var w1 = worker('worker1');
var w2 = worker('worker2');
var w3 = worker('worker3');
var wall = wall([w1,w2,w3]);
wall.run();
w1.load();
w3.load();
setTimeout(function(){w2.load();}, 500);
setTimeout(function(){ w3.load(); }, 2000);
setTimeout(function(){ w2.load(); }, 2700);
setTimeout(function(){ w1.load(); }, 3200);
setTimeout(function(){ w1.load(); }, 4000);
setTimeout(function(){ w3.load(); }, 4500);
setTimeout(function(){ w2.load(); }, 5000);
// end
function log(msg){
if(!(msg instanceof Array) ){ msg = [msg]; }
msg.forEach(function(m){
$('#out').append($('<p/>').text(m));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment