Created
March 13, 2015 15:50
-
-
Save dclowd9901/ad7e004d6a315d9bd838 to your computer and use it in GitHub Desktop.
Async Queuer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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