Skip to content

Instantly share code, notes, and snippets.

@imaximix
Created December 22, 2015 09:24
Show Gist options
  • Save imaximix/cce992a2127a75cebf4a to your computer and use it in GitHub Desktop.
Save imaximix/cce992a2127a75cebf4a to your computer and use it in GitHub Desktop.
var queue = function () {
var tasksToExecute = [],
lastExecutedIndex = -1,
$deferred, taskFailed = false;
function reset() {
lastExecutedIndex = -1;
taskFailed = false;
}
function pop() {
lastExecutedIndex = lastExecutedIndex + 1;
return tasksToExecute[lastExecutedIndex];
}
function init() {
// Get the first item
var task = pop();
if (taskFailed) {
return;
}
if (!task) {
reset();
$deferred.resolve();
return;
}
// Execute the task
var promise = task.apply(this);
// Wait for the promises response
promise
.then(function () {
init();
})
.fail(function () {
reset();
taskFailed = true;
$deferred.reject();
});
}
function process(tasks) {
if (!_.isArray(tasks)) throw new TypeError('tasks should be an array');
$deferred = $.Deferred();
tasksToExecute = tasks;
init();
return $deferred.promise();
}
return {
process: process
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment