public
Last active

async / sync queue of functions.

  • Download Gist
jobsQueue.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
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' }
}
]);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.