Skip to content

Instantly share code, notes, and snippets.

@Maksims
Last active December 16, 2015 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Maksims/5466319 to your computer and use it in GitHub Desktop.
Save Maksims/5466319 to your computer and use it in GitHub Desktop.
async / sync queue of functions.
function jobsQueue(jobs) {
if (jobs && jobs instanceof Array && jobs.length > 0) {
var count = jobs.length;
var i = -1;
var next = function() {
if (++i < count) jobs[i](next);
}
next();
}
}
function jobsQueueAsync(jobs, complete) {
if (jobs && jobs instanceof Array && jobs.length > 0) {
var count = jobs.length;
var done = function() {
if (--count == 0 && complete) complete();
}
for(var i = 0, len = jobs.length; i < len; ++i) {
jobs[i](done)
}
}
}
// usage example
var data = { };
jobsQueue([
function(next) {
data.value = 1; // 1
next();
},
function(next) {
data.value += 10; // 11
setTimeout(function() { // create async call
data.value *= 2; // 22
next();
}, 20);
},
function(next) {
data.value = 'test ' + data.value; // 'test 22'
next();
},
function() {
console.log(data); // { value: 'test 22' }
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment