Created
September 30, 2013 20:41
-
-
Save warash/6769958 to your computer and use it in GitHub Desktop.
Buffers tasks - and forcess execution one by one #corutines #pipeline #deferred
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
/* Class: Buffer | |
* methods: append | |
* | |
* Constructor: takes a function which will be the task handler to be called | |
* | |
* .append appends a task to the buffer. Buffer will only call a task when the | |
* previous task has finished | |
*/ | |
var Buffer = function(handler) { | |
var tasks = []; | |
// empty resolved deferred object | |
var deferred = $.when(); | |
// handle the next object | |
function handleNextTask() { | |
// if the current deferred task has resolved and there are more tasks | |
if (deferred.isResolved() && tasks.length > 0) { | |
// grab a task | |
var task = tasks.shift(); | |
// set the deferred to be deferred returned from the handler | |
deferred = handler(task); | |
// if its not a deferred object then set it to be an empty deferred object | |
if (!(deferred && deferred.promise)) { | |
deferred = $.when(); | |
} | |
// if we have tasks left then handle the next one when the current one | |
// is done. | |
if (tasks.length > 0) { | |
deferred.done(handleNextTask); | |
} | |
} | |
} | |
// appends a task. | |
this.append = function(task) { | |
// add to the array | |
tasks.push(task); | |
// handle the next task | |
handleNextTask(); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment