Created
December 22, 2015 09:24
-
-
Save imaximix/cce992a2127a75cebf4a to your computer and use it in GitHub Desktop.
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
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