Skip to content

Instantly share code, notes, and snippets.

@dclowd9901
Created March 13, 2015 15:50
Show Gist options
  • Save dclowd9901/ad7e004d6a315d9bd838 to your computer and use it in GitHub Desktop.
Save dclowd9901/ad7e004d6a315d9bd838 to your computer and use it in GitHub Desktop.
Async Queuer
function asyncFunction(){
var deferred = Promise.defer();
setTimeout(function(){
console.log('ping');
deferred.resolve();
},3000);
return deferred.promise;
}
function AsyncQueuer(){
var queue = [],
running = false;
function runQueue(){
var first = queue.shift();
running = true;
if (first) {
first.promisable.apply(first.context).then(function() {
first.deferral.resolve();
runQueue();
},
function() {
first.deferral.reject();
runQueue();
});
} else {
running = false;
}
}
return {
add: function(promisable, context) {
var deferred = Promise.defer();
queue.push({
promisable: promisable,
deferral: deferred,
context: context || window
});
if (!running) {
runQueue();
}
return deferred;
}
};
}
var asyncQueuer = new AsyncQueuer();
asyncQueuer.add(asyncFunction);
asyncQueuer.add(asyncFunction);
asyncQueuer.add(asyncFunction);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment