Last active
December 16, 2015 16:49
-
-
Save Maksims/5466319 to your computer and use it in GitHub Desktop.
async / sync queue of functions.
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
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