Skip to content

Instantly share code, notes, and snippets.

@nescalante
Last active August 29, 2015 13:58
Show Gist options
  • Save nescalante/10043230 to your computer and use it in GitHub Desktop.
Save nescalante/10043230 to your computer and use it in GitHub Desktop.
Array batch execution
function batch(array, size, callback, done) {
var index = 0,
processed = 0;
while (index < size) {
next();
}
function next() {
var item = array[index];
if (item) {
callback(item, index, function () {
processed++;
if (array[index]) {
next();
}
else if (processed === array.length && done) {
done();
}
});
}
index++;
}
}
@nescalante
Copy link
Author

Kill the server with simultaneous calls

Usage

var batchSize = 3;
var array = ["a", "b", "c", "d", "e"];

batch(array, batchSize, function(item, index, next) {
    someAsyncFunc(item, function callback() {
        doSomeStuff();

        // we are done, now lets go to the next step
        next();
    });
}, function () {
    // all calls have been succeeded, do something about
    finishProcess();
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment